MyBatisPlus Primer (SpringBoot)

An overview,

Mybatis is a hot lightweight persistent layer framework. Usually need to write XML files, write SQL can be convenient to operate the database. It’s a flexible tool for manipulating databases, but I won’t repeat it here.

Mybatis-Plus (MP for short) is an enhancement tool of Mybatis. It only enhances Mybatis without modification. It’s more efficient.

Internal encapsulation of common CURD operations can be achieved by calling methods to operate the database without writing SQL statements.

Here is how to experience Plus’s efficiency for single-table CRUD.

Two, actual combat use

1, environmental

  • SpringBoot
  • Mysql
  • MybatisPlus

2. Data & code description

Create a database named user:

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `own_email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL.PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1.'JoJo'.'23'.'[email protected]');
INSERT INTO `user` VALUES (2.'kit'.'22'.'[email protected]');
INSERT INTO `user` VALUES (23.'bii'.'22'.'[email protected]');

SET FOREIGN_KEY_CHECKS = 1;
Copy the code

3. Actual combat operation

1- Import dependencies

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.1.0</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Copy the code

2- Configure the database

# configure data source
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    name: root
    password: 12345
    url: jdbc:mysql:///test
Copy the code

3- Write the entity class User corresponding to the database

@Data
@TableName("user") // Table name mapping
public class UserPO {
	// Specify id, the type of id
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    // Specify the mapping of field names
    @TableField("name")
    private String name;

     // Specify the mapping of field names
    @TableField("age")
    private String age;

     // Specify the mapping of field names
    @TableField("own_email")
    private String Email;
}

Copy the code

Entity classes use Lombok to simplify writing

4 – write Mapper

/ * * *@author Hacah
 * @date2021/5/19 10:00 * /
public interface UserMapper extends BaseMapper<UserPO> {}Copy the code

BaseMapper inherited from Mybatis-Plus

5- Write test code

@Autowired
private UserMapper userMapper;

@Test
void contextLoads(a) {

    List<UserPO> userPOS = userMapper.selectList(null);
    System.out.println(userPOS);

}
Copy the code

Results:

[UserPO(id=1, name=JoJo, age=23, [email protected]), UserPO(id=2, name=kit, age=22, [email protected])]
Copy the code

4. Introduction of CRUD operation methods

1 – query

Query one:
1.slelectByOne

Query a piece of data by id.

UserPO = usermapper.selectById (1); System.out.println(userPO);Copy the code

Results:

UserPO(id=1, name=JoJo, age=23, Email=1215135@jojo.com)
Copy the code
2.selectOne

If the number of query items exceeds 1, an error message is displayed.

// 2
QueryWrapper<UserPO> userPOQueryWrapper = new QueryWrapper<>();
userPOQueryWrapper.eq("age"."22"); // add age = 22 to SQL
System.out.println(userMapper.selectOne(userPOQueryWrapper));
// SELECT id,name,age,own_email AS Email FROM user WHERE age = 22; 
Copy the code

The QueryWrapper class can construct the conditions for a query

QueryWrapper

This is the class for concatenating conditions that are passed to the class to construct conditions for SQL operations

For example, or, and, =, between… in.. , etc.

More than a query
1.selectByMap

Query multiple pieces of data using the Map.

HashMap<String, Object> stringObjectHashMap = new HashMap<>(); stringObjectHashMap.put("age", 22); System.out.println(userMapper.selectByMap(stringObjectHashMap));Copy the code

Results:

[UserPO(id=2, name=kit, age=22, Email=63362@kit.com), 
 UserPO(id=3, name=bii, age=22, Email=354643@bii.com)]
Copy the code
2.selectBatchIds

Batch query by ID

// 4. Use an ID to query for more data
ArrayList<Integer> userPOS = new ArrayList<>();
userPOS.add(1);
userPOS.add(2);
System.out.println(userMapper.selectBatchIds(userPOS));
Copy the code

Results:

[UserPO(id=1, name=JoJo, age=23, Email=1215135@jojo.com), 
 UserPO(id=2, name=kit, age=22, Email=63362@kit.com)]
Copy the code

2 – new

1.update

Pass in an entity class to add a new piece of data

 // 5. Add data
UserPO userPO = new UserPO();
userPO.setAge("12");
userPO.setName("fibs");
userPO.setEmail("[email protected]");
userMapper.insert(userPO);
Copy the code

Results:

3 to modify

1.updateById

An entity class is passed in with an ID update

 // 6. Modify data
UserPO userPO = new UserPO();
userPO.setId(1);
userPO.setAge("31");
userMapper.updateById(userPO);
Copy the code

Results:

2.update

Pass in an entity class and a condition class to update the data

 // 6. Modify data by conditions
UserPO userPO = new UserPO();
userPO.setAge("31");

QueryWrapper<UserPO> userPOQueryWrapper = new QueryWrapper<>();
userPOQueryWrapper.isNotNull("age"); // create condition where age! = null

userMapper.update(userPO,userPOQueryWrapper);
Copy the code

Results:

If the age is not null, change it to 31

4 – removed

Select * from (select * from);

  • DeleteById deleteById

  • DeleteByMap Delete using the map

  • Delete Delete by condition

  • DeleteBatchIds Batch deletes by ID


Delete is demonstrated here only, using conditions to delete data

Delete data whose ID is less than or equal to 1

userMapper.delete(new QueryWrapper<UserPO>().le("id".1));
Copy the code

Results:

Third, summary

This blog is an introductory description. First understand the enhancement of MybatisPlus, and experience it through practice, to certify its running results. Let’s create an image of this for later use, and solving the problems we encounter later is what we’ve been learning for.