This is the 8th day of my participation in the August Text Challenge.More challenges in August
preface
In the beginning, to use a database in Java, we needed to use JDBC, create a Connection, ResultSet, etc. Then we encapsulated JDBC operations, creating a number of utility classes like DBUtil. Then gradually, a series of persistence layer frameworks emerged: Hibernate, JPA, Mybatis and so on. The features of each framework are as follows:
- Hibernate: A fully automatic ORM framework that realizes the mapping between tables and Java objects in a database. By calling the methods of Java objects, we can realize the operation of data in a database table. And with this framework, we can access different databases without changing the code.
- JPA: This is a specification that defines various operations to access a database and defines a consistent way to manipulate the database.
- Mybatis: We need to write XML configuration files, we need to write SQL statements in XML to access the database, and everything needs to be done through XML. CRUD for a single table can also be done using XML files. This raises the bar for us developers, who need to be very familiar with the SQL language to do it.
In fact, using Mybatis to develop the persistence layer has greatly reduced the workload of the staff, but its use still needs a certain threshold. With the advent of Mybatis Plus, the threshold has been lowered even further. So today we will see, Mybatis-Plus exactly how to further achieve Mybatis enhancement.
Mybatis – Plus introduction
What is MyBatis – Plus
Mybatis-Plus: Designed to simplify development
MyBatis-Plus (MP for short) is an enhancement tool based on MyBatis, which enhances the basic functions of MyBatis without making any changes. It enables us to directly upgrade Mybatis to Mybatis- Plus on the project developed by Mybatis. Just as it has positioned itself, it can help us further simplify the development process and improve development efficiency.
In fact, Mybatis-Plus can be regarded as another encapsulation of Mybatis. After the upgrade, the API provided by Mybatis-Plus can be easily realized for CRUD operations of single tables. In addition, it also provides various query methods, pagination and other behaviors. Most importantly, developers don’t have to write XML, which makes development much easier.
Its official website is mp.baomidou.com.
The characteristics of the Mybatis – Plus
- No intrusion, small loss
- Powerful CURD operations
- Lambda calls are supported
- Supports automatic generation of primary keys
- Support custom global generic schema
- ActiveRecord mode is supported
- Built-in code generator, paging plug-in, performance analyzer, and global interceptor plug-in
- …
Mybatis – Plus structure
Quick Start Example
Database preparation
We still use the examples provided in the official documents to carry out the work, but I will not use MySQL to carry out the work, but based on PostgreSQL. On the one hand, it is different from the official work, and on the other hand, it is convenient for me to learn and force me to master a new technology more quickly.
So let’s first create a database and enter:
drop database if exists mydb;
create database mydb;
\c mydb;
Copy the code
Then create an employee table, mainly have ID, name, sex, email four attributes.
create table employee(
id int primary key not null,
name varchar(100) null,
sex varchar(10) null,
email varchar(255) null
)
Copy the code
Then insert some data:
DELETE FROM employee;
INSERT INTO employee (id, name, sex, email) VALUES
(1.'Joe'.'male'.'[email protected]'),
(2.'bill'.'woman'.'[email protected]'),
(3.'Cathy'.'male'.'[email protected]');
Copy the code
SpringBoot project
Here I use IDEA to create a SpringBoot project, after the creation of the main need to pay attention to the following points.
- Add the dependent
In addition to the necessary dependencies needed to create a SpringBoot project, we also need to introduce MP and PostgreSQL dependencies.
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
Copy the code
- Database Configuration
After the dependency is added, add the database configuration to the application.yml configuration file (note: the officially created configuration file is application.properties, we need to manually change its suffix to.yml).
spring:
datasource:
url: jdbc:postgresql://localhost:5432/mydb
password: 12345
username: postgres
driver-class-name: org.postgresql.Driver
application:
name: employee
Copy the code
- Overall project structure
After the project is created, our final project directory structure is as follows:
coding
After preparing the database and setting up the SpringBoot project, the next step is coding.
- Entity class writing
The entity class corresponds to the employee table we just created. Because Lombok is used here, you can see that there is an @data annotation on the class, but there are no getters and setters, which simplifies the code. If you don’t know about Lombok, you should check it out, and I’ll probably write an article about it later. You can pay attention to that.
package com.cunyu.employee.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* Created with IntelliJ IDEA.
*
* @author : cunyu
* @version : 1.0
* @project : Employee
* @package : com.cunyu.employee.entity
* @className : Employee
* @createTime: 2021/8/7 *@description: Employee entity class */
@Data
@TableName("employee")
public class Employee {
/** * Employee id */
@TableId("id")
private Long id;
/** * Employee name */
private String name;
/** ** Gender of employee */
private String sex;
/**
* 员工邮件
*/
private String email;
}
Copy the code
- Mapper interface
Here EmployeeMapper is inherited from BaseMapper in MP, which has provided many methods for us to use.
package com.cunyu.employee.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cunyu.employee.entity.Employee;
/**
* Created with IntelliJ IDEA.
*
* @author : cunyu
* @version : 1.0
* @project : Employee
* @package : com.cunyu.employee.mapper
* @className : EmployeeMapper
* @createTime: 2021/8/7 then *@description: Employee Mapper class */
public interface EmployeeMapper extends BaseMapper<Employee> {}Copy the code
Here are some of the methods provided in BaseMapper. By inheriting this interface, you can get CRUD functionality without writing mapper.xml.
package com.baomidou.mybatisplus.core.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Param;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/** * The CRUD function can be obtained by Mapper without having to write the mapper. XML file * <p@author hubin
* @sinceThe 2016-01-23 * /
public interface BaseMapper<T> extends Mapper<T> {
/** * Insert a record **@paramEntity Entity object */
int insert(T entity);
/** * delete ** based on ID@paramId Primary key ID */
int deleteById(Serializable id);
/** * Drop the record ** according to the columnMap condition@paramColumnMap Table field map object */
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/** * Delete record ** according to entity condition@paramThe queryWrapper entity object encapsulates the action class (which can be null, where the entity is used to generate the WHERE statement) */
int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/** * delete (batch delete by ID) **@paramIdList List of primary key ids (cannot be null or empty) */
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/** * Change ** according to ID@paramEntity Entity object */
int updateById(@Param(Constants.ENTITY) T entity);
/** * Update the record ** according to the whereEntity condition@paramEntity Entity object (set conditional value, which can be null) *@paramThe updateWrapper entity object encapsulates the action class (which can be null, where the entity is used to generate the WHERE statement) */
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/** * query ** by ID@paramId Primary key ID */
T selectById(Serializable id);
/** * query (by ID) **@paramIdList List of primary key ids (cannot be null or empty) */
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/** * Query (based on columnMap condition) **@paramColumnMap Table field map object */
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/** * Query a record ** according to the entity condition@paramThe queryWrapper entity object encapsulates the action class (which can be null) */
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/** * Query the total number of records according to the Wrapper condition **@paramThe queryWrapper entity object encapsulates the action class (which can be null) */
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/** * query all records ** according to entity condition@paramThe queryWrapper entity object encapsulates the action class (which can be null) */
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/** * Query all records ** according to the Wrapper condition@paramThe queryWrapper entity object encapsulates the action class (which can be null) */
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/** * Query all records according to the Wrapper condition * <p> Note: only return the value of the first field </p> **@paramThe queryWrapper entity object encapsulates the action class (which can be null) */
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/** * Query all records according to entity condition **@paramPage paging query criteria (can be rowbound.default) *@paramThe queryWrapper entity object encapsulates the action class (which can be null) */
<P extends IPage<T>> P selectPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/** * Query all records (and turn pages) according to the Wrapper condition **@paramPage paging query criteria *@paramThe queryWrapper entity object encapsulates the action class */
<P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}
Copy the code
- Adding packet Scanning
After the Mapper is set up, we need to start the class to add the annotation @mapperscan () for package scanning.
package com.cunyu.employee;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.cunyu.employee.mapper")
public class EmployeeApplication {
public static void main(String[] args) { SpringApplication.run(EmployeeApplication.class, args); }}Copy the code
- test
Ok, after completing the above steps, we are ready to test the interface. To the main application EmployeeApplicationTests, add the following code for the interface test.
package com.cunyu.employee;
import com.cunyu.employee.entity.Employee;
import com.cunyu.employee.mapper.EmployeeMapper;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class EmployeeApplicationTests {
@Test
void contextLoads(a) {}@Autowired
private EmployeeMapper employeeMapper;
@Test
void testGetAll(a) {
List<Employee> employees = employeeMapper.selectList(null);
Assert.assertEquals(3, employees.size()); System.out.println(employees); }}Copy the code
You can see that the test succeeded after executing our test code, indicating that the interface is fine.
The thing to note here is assert.assertequals (3, employees.size()); For more information on Junit testing, see my previous article: Ditch traditional annotated tests and Embrace Junit Unit Tests.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
Copy the code
conclusion
This is the end of today’s article, mainly introduced Mybatis-Plus some related introduction, and then is to use Mybatis-Plus to carry out an example of our operation. However, I am using PostgreSQL, which is similar to MySQL. Many operations are the same, so don’t worry.
Finally, the creation is not easy, if this article is helpful to you, but also ask your friends can one key three connect. Thanks for your support, and see you next time!