1 Core Functions

  • General CRUD: After the Mapper interface is defined, you only need to inherit the BaseMapper interface to obtain the general function of adding, deleting, modifying, and querying, without writing any interface methods or configuration files
  • Conditional constructors: Can be used to concatenate SQL statements and support complex SQL such as sorting and grouping queries through EntityWrapper classes
  • Code generator: support a series of policy configuration and global configuration, better than MyBatis code generation

2 Basic Configuration

2.1 Adding core dependencies

<! <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector- Java </artifactId> <scope>runtime</scope> </dependency> <! -- lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional>  </dependency> <! <dependency> <groupId>com.baomidou</groupId> < artifactId > mybatis - plus - the boot - starter < / artifactId > < version > 3.4.0 < / version > < / dependency > <! <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> The < version > 3.4.1 track < / version > < / dependency > <! <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> The < version > 2.0 < / version > < / dependency >Copy the code

2.2 Configuration file application.yml

spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver username: root password: suruomo url: JDBC: mysql: / / 127.0.0.1:3306 / demo? useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8 server: port: 8070Copy the code

Functional experience

3.1 general CRUD

Entity class

package com.suruomo.mybatisplus.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.util.Date; /** * @Author: suruomo * @Date: 2020/8/25 14:38 * @Description: */ @data@tablename (value = "sys_user") public class SysUser {/** * Login account * type = IdType.INPUT Indicates that primary key * is changed to AUTO to increment */ @TableId(type = IdType.INPUT) private String userId; /** * private String userName; /** * private String email; /** * mobile phonenumber */ private String phonenumber; /** * user sex (0 male, 1 female, 2 unknown) */ private String sex; /** * password */ private String password; /** * Account status (0 normal 1 Disabled) */ private String status; /** * private String delFlag; /** * private String loginIp; /** * private Date loginDate; /** * private String createBy; /** * createTime */ @tablefield (fill = FieldFill.INSERT) private Date createTime; /** * update */ private String updateBy; / / @tableField (fill = FieldFill.INSERT_UPDATE) private Date updateTime; }Copy the code

Mapper interfaces

package com.suruomo.mybatisplus.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.suruomo.mybatisplus.entity.SysUser; import org.apache.ibatis.annotations.Mapper; /** * @Author: suruomo * @Date: 2020/8/25 14:40 * @Description: */ @mapper public interface SysUserMapper extends BaseMapper<SysUser> {}Copy the code

General CRUD methods:

The Service layer

package com.suruomo.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.suruomo.mybatisplus.entity.SysUser;

/**
 * @Author: suruomo
 * @Date: 2020/8/25 19:34
 * @Description:
 */
public interface SysUserService extends IService<SysUser> {
}
Copy the code
package com.suruomo.mybatisplus.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suruomo.mybatisplus.mapper.SysUserMapper;
import com.suruomo.mybatisplus.entity.SysUser;
import com.suruomo.mybatisplus.service.SysUserService;
import org.springframework.stereotype.Service;

/**
 * @Author: suruomo
 * @Date: 2020/8/25 19:36
 * @Description:
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

}
Copy the code

test

/ @runwith (springrunner.class) @SpringbooTtest Class MapperTest {@resource private SysUserMapper sysUserMapper; @test void selectList() {List<SysUser> userList = sysusermapper.selectList (null); userList.forEach(System.out::println); @test void selectByPage() {Page<SysUser> Page = new Page<>(1, 3); IPage<SysUser> userIPage = sysUserMapper.selectPage(page, null); System.out.println(" total number of entries: "+ page.getTotal()); System.out.println(" total pages "+ Page.getPages ()); List<SysUser> list=userIPage.getRecords(); list.forEach(System.out::println); /** * insert */ @test void insert(){SysUser user=new SysUser(); user.setUserId("25"); user.setUserName("susu"); sysUserMapper.insert(user); } @test void deleteById(){sysusermapper.deletebyid (" ZXC "); } /** * delete from map */ @test void DeleteByMap(){HashMap<String, Object> map = new HashMap<>(); map.put("user_id","25"); sysUserMapper.deleteByMap(map); } /** * update by id */ @test void update(){SysUser user=new SysUser(); user=sysUserMapper.selectById("ry"); user.setUserName("ry"); sysUserMapper.updateById(user); }}Copy the code

3.2 Automatic fill function

It is common to encounter data that is populated in the same way each time, such as when records were created, when they were updated, and so on. We can use MyBatis Plus autofill function to complete the assignment of these fields: 1. 2. Add annotations to the entity class

/** * createTime */ @tablefield (fill = FieldFill.INSERT) private Date createTime; / / @tableField (fill = FieldFill.INSERT_UPDATE) private Date updateTime;Copy the code

3. Realize the meta-object processor interface

@Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("createTime", new Date(), metaObject); this.setFieldValByName("updateTime", new Date(), metaObject); } @Override public void updateFill(MetaObject metaObject) { this.setFieldValByName("updateTime", new Date(), metaObject); }}Copy the code

3.3 Paging

MyBatis Plus has its own paging plug-in, as long as the simple configuration can achieve paging function configuration class:

@configuration Public class PaginationConfig {@bean public PaginationInterceptor PaginationInterceptor () { return new PaginationInterceptor (); }}Copy the code

Use:

@test void selectByPage() {Page<SysUser> Page = new Page<>(1, 3); IPage<SysUser> userIPage = sysUserMapper.selectPage(page, null); System.out.println(" total number of entries: "+ page.getTotal()); System.out.println(" total pages "+ Page.getPages ()); List<SysUser> list=userIPage.getRecords(); list.forEach(System.out::println);Copy the code

3.4 EntityWrapper conditional constructor

Mybatis-Plus uses EntityWrapper (EW, a query Condition constructor wrapped by MP) or Condition (similar to EW) to allow users to build query conditions freely, which is simple and convenient without additional burden and can effectively improve development efficiency

Entity wrapper, mainly used to deal with SQL concatenation, sorting, entity parameters query, etc

Note: Database fields are used, not Java property names

For details about the parameters, see baomidou.com/guide/wrapp…

Use:

@RunWith(SpringRunner.class) @SpringBootTest public class QueryWrapperTest { @Resource private SysUserMapper sysUserMapper; @Test public void selectByInfo(){ QueryWrapper<SysUser> wrapper = new QueryWrapper<>(); / / find the gender is 0, the name for a beginning wrapper. Select (" user_id ", "user_name", "email", "sex"). The eq (" sex ", 0) like (" user_name ", "a"); List<SysUser> users = sysUserMapper.selectList(wrapper); users.forEach(user -> System.out.println(user)); }}Copy the code

3.5 Code Generator

AutoGenerator is the code generator of MyBatis-Plus, through which the code of Entity, Mapper, Mapper XML, Service, Controller and other modules can be generated quickly. Greatly improved the development efficiency.

Public class GenerateCode {public static void main(String[] args) {// Need to build a code automatic generator object AutoGenerator MPG = new AutoGenerator(); GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath+"/src/main/java"); gc.setAuthor("suruomo"); // Author name gc.setopen (false); // Customize the file name, note that %s will automatically populate the table entity attributes! gc.setServiceName("%sService"); gc.setControllerName("%sController"); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setMapperName("%sMapper"); gc.setXmlName("%sMapper"); mpg.setGlobalConfig(gc); // set DataSourceConfig DSC = new DataSourceConfig(); DSC. SetUrl (" JDBC: mysql: / / 127.0.0.1:3306 / demo? useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); // dsc.setDriverName("com.mysql.jdbc.Driver"); //mysql5.6 following the driver dsc.setusername ("root"); dsc.setPassword("suruomo"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); PackageConfig PC = new PackageConfig(); pc.setParent("com.suruomo"); / / package name PC. SetModuleName (" mybatisplus "); // module name pc.setentity ("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setController("controller"); mpg.setPackageInfo(pc); //4, StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("sys_user","aluminum","sys_log"); // Set the name of the table to be mapped strategy.setnaming (namingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); // Automatic lombok; strategy.setLogicDeleteFieldName("deleted"); strategy.setRestControllerStyle(true); / / rest request / / automatically underline, such as localhost: 8080 / hello_id_2 strategy. SetControllerMappingHyphenStyle (true); mpg.setStrategy(strategy); mpg.execute(); // execute}}Copy the code