CRUD of MyBatisPlus Service layer

It will be the top of the mountain

| @Author: TTODS

MyBatisPlus framework series article directory:


Similar to Mapper layer, MybatisPlus also provides a Service layer interface with general CRUD function. This paper will introduce how to use the base classes and interfaces provided by MybatisPlus to build our Service layer and how to use the general CRUD of Service layer

Create UserService interface

Create a UserService interface in the package com.example.service and make it inherit the iservice < T > interface provided by mybatis plus (T represents the corresponding entity class type).

package com.example.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.pojo.User;

public interface UserService extends IService<User> {


Create UserServiceImpl class

Create a UserServiceImpl class in the package com.example.service.impl, and make it inherit the serviceimpl < m extensions basemapper < T >, t > classes provided by mybatis plus (T represents the corresponding entity class type), and implement the UserService interface created in the previous step. Then add the @ Service annotation.

package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import com.example.service.UserService;
import org.springframework.stereotype.Service;

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

After creation, the project structure is as follows:

So far, although we have not written any code in UserService, it already has the basic CRUD function provided by mybatis plus.

CRUD of Service layer

save method

boolean save(T entity); // Insert a record
boolean saveBatch(Collection<T> entityList);// Insert (batch), the default batch size is 1000
boolean saveBatch(Collection<T> entityList, int batchSize);// Insert (batch)
public class ServiceCurdTests {
    UserService userService;
    public void testSave(){
        // Create entity class object
        User user = new User();
        //  Call the save method;

Generated sql statement and output:

==>  Preparing: INSERT INTO user ( name, age, gender, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: Garrison(String), 45(Integer), 1(Integer),
<==    Updates: 1

View the database and modify it successfully.

saveOrUpdate method

boolean saveOrUpdate(T entity); // Update record exists in TableId annotation. Insert a record
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);// If the updateWrapper attempts to update, do you want to continue with the saveOrUpdate(T) method
boolean saveOrUpdateBatch(Collection<T> entityList);// Batch modify insert
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);// Batch modify insert

saveOrUpdate test 1:

    public void testSaveOrUpdate(){
        User user = new User();

Generated Sql code:

==>  Preparing: SELECT id,name,age,gender,email FROM user WHERE id=?
==> Parameters: 7(Integer)
<==      Total: 1
==>  Preparing: UPDATE user SET age=? WHERE id=?
==> Parameters: 1(Integer), 7(Integer)
<==    Updates: 1

saveOrUpdate test 2:

    public void testSaveOrUpdate1(){
        User user = new User();

Generated sql code:

==>  Preparing: SELECT id,name,age,gender,email FROM user WHERE id=?
==> Parameters: 8(Integer)
<==      Total: 0
==>  Preparing: INSERT INTO user ( age ) VALUES ( ? )
==> Parameters: 1(Integer)
<==    Updates: 1

It can be seen from the above two tests that the updateOrSave method will first run a Select statement to judge whether the record exists through the primary key field. If it exists, run the Update statement. Otherwise, run the Insert statement, and the null attribute in the entity class will not be updated.

remove method

boolean remove(Wrapper<T> queryWrapper);// Delete the record according to the entity condition
boolean removeById(Serializable id); // Delete by ID
boolean removeByMap(Map<String, Object> columnMap);// Delete the record according to the columnMap condition
boolean removeByIds(Collection<? extends Serializable> idList);// Delete (batch delete according to ID)

update method

boolean update(Wrapper<T> updateWrapper);// According to the UpdateWrapper condition, sqlset needs to be set for updating records
boolean update(T updateEntity, Wrapper<T> whereWrapper);// Update the record according to the whereWrapper condition
boolean updateById(T entity);// Select modify according to ID
boolean updateBatchById(Collection<T> entityList);// Batch update by ID
boolean updateBatchById(Collection<T> entityList, int batchSize);// Batch update by ID
    public void update(){
        User user = new User();
        // The value in the first parameter entity class object will generate the corresponding set clause
        userService.update(user,new UpdateWrapper<User>().eq("id",8));

Generated sql:

==>  Preparing: UPDATE user SET name=?, age=?, gender=?, email=? WHERE (id = ?)
==> Parameters: Hailie(String), 32(Integer), 0(Integer),, 8(Integer)
<==    Updates: 1

View the database and modify it successfully.

A strange question

Suppose that when we use the Boolean update (t updateentity, wrapper < T > where wrapper) method, what happens if we use updatewrapper in the second parameter and set it to conflict with the parameters in the first entity class object?

This example is just a whim in my learning process [doge]... High-risk code... Do not imitate... [doge]

    public void update01(){
        User user = new User();
        //Set the age here to 30
        // In the second parameter, set the age to 29
        userService.update(user,new UpdateWrapper<User>().eq("id",8).set("age",29));

Generated sql code:

==>  Preparing: UPDATE user SET age=?, age=? WHERE (id = ?)
==> Parameters: 30(Integer), 29(Integer), 8(Integer)
<==    Updates: 1

It can still run successfully, but age is set twice in the generated sql statement. Because age=29 is later, the final result in the database is 29

Get method

Query a record by criteria

T getById(Serializable id);// Query by ID
T getOne(Wrapper<T> queryWrapper);// Query a record according to the Wrapper. If there are multiple result sets, exceptions will be thrown. Take one at random and add the limiting condition wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper, boolean throwEx);// Query a record according to the Wrapper
Map<String, Object> getMap(Wrapper<T> queryWrapper);// Query a record according to the Wrapper
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);// Query a record according to the Wrapper

List method

Query multiple records by criteria

List<T> list();// Query all
List<T> list(Wrapper<T> queryWrapper);// Query list
Collection<T> listByIds(Collection<? extends Serializable> idList);// Query (batch query by ID)
Collection<T> listByMap(Map<String, Object> columnMap);// Query (based on columnMap criteria)
List<Map<String, Object>> listMaps();// Query all lists
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);// Query list
List<Object> listObjs();// Query all records
<V> List<V> listObjs(Function<? super Object, V> mapper);// Query all records
List<Object> listObjs(Wrapper<T> queryWrapper);// Query all records according to Wrapper conditions
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);// Query all records according to Wrapper conditions

Page method

Please read ~ ~ < mybatis plus paging function > >~~

Count method

int count();// Total records queried
int count(Wrapper<T> queryWrapper);// Query the total number of records according to Wrapper conditions
public void testCount(){
    int total = userService.count();
    int male = userService.count(new QueryWrapper<User>().eq("gender",1));
    int female = userService.count(new QueryWrapper<User>().eq("gender", 0));
    System.out.println(String.format("Total users: %d\n among:\n\t Male:\t%d\n\t female sex:\t%d",

Generated sql statement and output

==>  Preparing: SELECT COUNT( 1 ) FROM user WHERE (gender = ?)
==> Parameters: 0(Integer)
<==      Total: 1
 Total users: 8
	Male:	5
	female sex:	3

Chain query and chain update

public void testChainQuery(){
	QueryChainWrapper<User> query = new QueryChainWrapper<>(userMapper);
	// Query the id, name and age of all male users
	List<User> users ="id", "name", "age").eq("gender",0).list();
	for (User user : users) {

Generated sql statement and output:

public void testChainUpdate(){
    UpdateChainWrapper<User> query = new UpdateChainWrapper<>(userMapper);
    // Increase the age of all female users by 1
    query.setSql("age = age+1").eq("gender",1).update();

Generated sql statement:

==>  Preparing: UPDATE user SET age = age+1 WHERE (gender = ?)
==> Parameters: 1(Integer)
<==    Updates: 5

Previous: CRUD of MyBatisPlus Mapper layer
Next: Paging function provided by MyBatisPlus


Tags: Java Spring Boot Back-end

Posted on Mon, 25 Oct 2021 05:14:05 -0400 by RedOrbit