This is the 9th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

preface

Mybatis is like a car, but with MybatisPlus it is definitely a nitrogen supercar.

Before the use of MybatisPlus, when querying a single table, you have to write SQL code silently, you have to generate basic code without code generator, once the parameters have multiple matching ways, then you have to copy a rewrite, or add an if condition, it is still uncomfortable.

But once you use MybatisPlus it’s like a different world.

See The MybatisPlus integration project based on SpringBoot

Basic Information

SQL

CREATE TABLE `student` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `info` varchar(255)  COMMENT 'zouzdc',
  `del_flag` tinyint(1) DEFAULT '0',
 `create_time` datetime,
 `create_by` varchar(255),
 `update_time` datetime ,
 `update_by` varchar(255),
 PRIMARY KEY (`id`)
) ;
Copy the code

Bean

@Data @NoArgsConstructor public class Student { /** * id */ @TableId private Long id; /** * other information */ private String info; 0 No 1 Yes */ @TABLelogic private String delFlag; /** * create Date */ @tableField (fill = FieldFill.INSERT) private Date createTime; /** * creator */ @tableField (fill = FieldFill.INSERT) private String createBy; /** * update Date */ @tableField (fill = FieldFill.INSERT_UPDATE) private Date updateTime; /** */ @tableField (fill = FieldFill.INSERT_UPDATE) private String updateBy; }Copy the code

MyBatisPlus Enhanced configuration – Field auto-fill

Normally,createTime and createBy, del_flag, tenant, etc. are assigned when input is inserted, and updateTime and updateBy are reassigned when data changes Dynamic fill function, let the program automatically help us do.

Where you need to move, you need to add a configuration class, and you need to add annotations on the required fields on the Bean

Annotate fields that need to be filled in@TableField(

The example is Student in the figure above

@tableField (fill = FieldFill.INSERT) will automatically fill the field when it is added. If the field has a value, it will not be overwritten

@tableField (fill = fieldfill.insert_update) this field is automatically filled in both new and updated, and overwritten if the field has a value

@tableField (fill = fieldfill.update) automatically fills the field in the UPDATE and overwrites it if it has a value

Fields automatically populate the configuration class

In the configuration class, customize the population rule for each field that requires automatic population data

@Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); this.strictInsertFill(metaObject, "createBy", String.class, getUserBy()); this.strictInsertFill(metaObject, "updateTime", Date.class, new Date()); this.strictInsertFill(metaObject, "updateBy", String.class, getUserBy()); // this.setFieldValbyName ("createTime",new Date(),metaObject); } @Override public void updateFill(MetaObject metaObject) { this.strictInsertFill(metaObject, "updateTime", Date.class, new Date()); this.strictInsertFill(metaObject, "updateBy", String.class, getUserBy()); } private String getUserBy(){private String getUserBy(){return "admin"; }}Copy the code

Logical deletion of data

Most tables in the service system cannot be deleted. Therefore, you need to use a field to define whether to delete a table. Only those who call MybatisPlus’s own methods and define the deleted field will be pseudo deleted, otherwise it will be true deleted. You need to handle the SQL you write yourself.

In this case, del_flag is used to define whether pseudo deletion is performed. 0 indicates no deletion and 1 indicates deletion

application.yml

Mybatis -plus: global-config: db-config: logic-delete-field: delFlag # Logic-delete-value: 1 # Logic-not -delete-value: 0 # Logic-not -delete-value: 0Copy the code

On the Bean class

0 No 1 Yes */ @TABLelogic private String delFlag;Copy the code

Since 3.3.0, @tablelogic can be configured globally in application.yml without fields on the Bean

Single table add delete change check use

Controller layer use add, delete, change and check

@RestController @RequestMapping("/student") public class StudentController { @Autowired(required = false) public StudentService studentService; @getMapping ("getById") public R getStudentById(Student Student){// Add studentService.save(Student); / / change studentService updateById (student); Student = studentService.getById(student.getid ()); / / delete studentService removeById (student getId ()); / / List with parameter query List < Student > zouzdc = studentService. LambdaQuery (). The eq (Student: : getInfo, "zouzdc"). The List (); return R.success(); }}Copy the code

The service layer uses add, delete, change, and search

Add and delete

@Service @Slf4j public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService { @Autowired(required = false) private StudentMapper studentMapper; @override public void mapper. insert(Student); @override public void mapper. insert(Student); / / change studentMapper updateById (student); / / check baseMapper selectById (student getId ()); / / delete baseMapper deleteById (student getId ()); // List<Student> List = this.lambdaQuery().eq(Student::getId, student.getid ()).list(); }}Copy the code

The default Mapper object in the Service is baseMapper, which is the same as studentMapper

Example for querying a single table condition

Lambda syntax

Query info equal to list of zouzdc

 List<Student> zouzdc = studentService.lambdaQuery().eq(Student::getInfo, "zouzdc").list();
Copy the code

Query an object whose INFO is equal to zouzdc

Student zouzdc = studentService.lambdaQuery().eq(Student::getInfo, "zouzdc").one();
Student zouzdc = studentService.lambdaQuery().eq(Student::getInfo, "zouzdc").last(" limit 1").one();
Copy the code

For non-unique data, if you use one() directly, non-single data error may occur. You can use last() to concatenate parameters to obtain the first data

Update the info field whose id=1

 studentService.lambdaUpdate().set(Student::getInfo,"zdc").eq(Student::getId,1).update();
Copy the code

Delete data where info is ‘zouzdc’

studentService.lambdaUpdate().set(Student::getInfo,"zouzdc").remove()
Copy the code

See the official documentation for more conditional constructs

Variant syntax is not recommended
 List<Student> zouzdc1 = studentService.list(new QueryWrapper<Student>().lambda().eq(Student::getInfo, "zouzdc"));
 Student zouzdc2 = studentService.getOne(new LambdaQueryWrapper<Student>().eq(Student::getInfo, "zouzdc"));
Copy the code

Paging query

Paging configuration class

@Configuration @MapperScan("zdc.enterprise.mapper.*") public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); / / set the biggest single page limit an amount, and 1 unlimited paginationInterceptor. SetLimit (1000); / / open the count of the join optimization, only part of the left join paginationInterceptor. SetCountSqlParser (new JsqlParserCountOptimize (true)); return paginationInterceptor; }}Copy the code

Lambda mode paging

public IPage<StudentDto> listPage(StudentDto vo){ return this.lambdaQuery() .eq(vo.getInfo() ! = null, Student::getInfo, vo.getInfo()) .eq(Student::getDelFlag, "0") .page(new Page(vo.getCurrent(), vo.getSize())); }Copy the code

Mixed mode paging

The Service layer

 public  Page<StudentDto> listPage(StudentDto vo){
 
        Page<Student> page = new Page(vo.getCurrent(), vo.getSize());
        page.addOrder(OrderItem.desc("a.create_time"));

        QueryWrapper<Student> wrapper = new QueryWrapper();
        wrapper.apply(" a.del_flag =0 ");
          wrapper.eq("a.info","zouzdc")
                .le("a.id",10);
        return baseMapper.listPage(page, wrapper);
    }
Copy the code

The Mapper layer

Page<StudentDto> listPage(@Param("page") Page<Student> page, @Param("ew") QueryWrapper<Student> wrapper);
Copy the code

@param (“ew”) is the fixed default

XML layer

<select id="listPage" resultType="zdc.enterprise.dto.StudentDto">
    select * from student a
    ${ew.customSqlSegment}

</select>
Copy the code

This is done by writing where conditions in SQL form in the service layer and then concatenating them to the end of the SQL in THE XML with ${ew.customSQLSegment}. Will bring the where

There are more… Do your own research

Source: author: ZOUZDC links: https://juejin.cn/post/7028963866063306760 re the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code