mybatis-plus
1. Introduction case:
Table creation:
create table user ( id bigint auto_increment comment 'Primary key ID' primary key, name varchar(30) null comment 'full name', age int null comment 'Age', email varchar(50) null comment 'mailbox', create_time datetime null comment 'Creation time', update_time datetime null comment 'Modification time', version int default 1 null comment 'Optimistic lock', deleted int(1) default 0 null comment 'Logical deletion' ) charset = utf8;
1.1 create a springboot project:
1.2 import dependency:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <!-- Database driven--> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies>
1. 3. Write configuration file: application Properties or application yaml
#Database link configuration spring: datasource: username: user name password: password url: jdbc:mysql://localhost:3306 / database description? useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8 driver-class-name: com.mysql.cj.jdbc.Driver #Log configuration mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #Logical delete configuration global-config: db-config: logic-delete-field: deleted logic-delete-value: 1 logic-not-delete-value: 0
2. Coding:
Class, package structure:
2.1 pojo entity class preparation:
/** * @ClassName User * @Description TODO * @Author 86188 * @DAte 2021/11/17 **/ @Data @AllArgsConstructor @NoArgsConstructor public class User { @TableId(type = IdType.AUTO)//Automatic growth private Long id; private String name; private Integer age ; private String email; @TableLogic//Delete annotation logically private Integer deleted; //Logical deletion @Version //Optimistic lock annotation private Integer version; @TableField(fill = FieldFill.INSERT)//When is the insert updated private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE)//Update when update private Date updateTime; }
2.2 mapper interface (userMapper):
/** * @ClassName UserMapper * @Description TODO * @Author 86188 * @DAte 2021/11/17 **/ @Mapper public interface UserMapper extends BaseMapper<User> { }
Note: annotate @ mapper annotation
Inherit basemapper < >
2.3 test:
@SpringBootTest class MybatisPlusApplicationTests { @Autowired private UserMapper userMapper; @Test void contextLoads () { List<User> userList = userMapper.selectList (null); for (User user : userList) { System.out.println ("user = " + user); } } }
Test results:
**Log configuration:
#Log configuration mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
2.4 adding: (userMapper.insert())
//insert @Test public void testInsert(){ User user = new User (null, "Sark", 23, "dsafrwr@qq.com",null,null,null,null); int insert = userMapper.insert (user); System.out.println (user); System.out.println (insert); }
Test results:
3. Primary key generation strategy:
3.1. Automatic growth: (Auto_increment)
@TableId(type = IdType.AUTO)//Automatic growth private Long id;
3.2 uuid: (unique value of production random):
@TableId(type = IdType.ASSIGN_UUID)//uuid private Long id;
3.3 mybatis plus built-in policy (snowflake algorithm) (also the default):
The ID generated by snowflake algorithm is a 64 bit long number and increases with time trend. It is roughly composed of four parts: first invalid character, timestamp difference, machine code and serial number.
As shown in the figure:
- First invalid symbol: the first bit is used as the symbol bit. Because we generate positive numbers, the first bit is uniformly 0.
- Timestamp: 41 bit, accurate to milliseconds. 41 bits can best represent 2 ^ 41-1 milliseconds, which is converted into 69 years.
- Machine code: it occupies 10 bits, of which the upper 5 bits are the data center ID and the lower 5 bits are the working node ID, which can accommodate 1024 nodes at most.
- Serial number: it takes up 12 bits. Each node starts accumulating every millisecond from 0. It can be accumulated to 4095 at most. A total of 4096 ID S can be generated.
@TableId(type = IdType.NONE)// private Long id;
4. Implement the update operation:
@Test //modify public void updateTest(){ User user = new User (); user.setAge (24); user.setId (7L); userMapper.updateById (user); System.out.println (user); }
5. Auto fill:
5.1 create_time and update_time
@TableField(fill = FieldFill.INSERT)//When is the insert updated private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE)//Update when update private Date updateTime;
5.2 MyMateObjectHandler configuration
@Component public class MyMateObjectHandler implements MetaObjectHandler { //Execute when insert ing @Override public void insertFill ( MetaObject metaObject ) { this.setFieldValByName ("createTime",new Date (),metaObject); this.setFieldValByName ("updateTime",new Date (),metaObject); } //When is update executed @Override public void updateFill ( MetaObject metaObject ) { this.setFieldValByName ("updateTime",new Date (),metaObject); } }
6. Optimistic lock (parallel operation):
Optimistic lock is used to solve dirty reading and unreal reading in case of thread conflict. Optimistic lock is produced to solve this problem; Optimistic lock thinks that there will be no data conflict by default, so it will formally detect whether the data conflict occurs when the data is submitted for update. If a conflict is found, it will return an error message to the user to let the user decide how to do it.
Use the version number to control. If a person changes the value, the version number + 1. As long as the version number is different, the operation cannot succeed.
6.1 . Add the @ Version annotation to the field of the entity class
@Version //Optimistic lock annotation @TableField(fill = FieldFill.INSERT)//Update on insert private Integer version;
6.2 write configuration class:
1. The default value is 1 when adding;
@Component public class MyMateObjectHandler implements MetaObjectHandler { //Execute when insert ing @Override public void insertFill ( MetaObject metaObject ) { this.setFieldValByName ("createTime",new Date (),metaObject); this.setFieldValByName ("updateTime",new Date (),metaObject); //Default value of insert: version=1 this.setFieldValByName ("version",1,metaObject); }
2. Configure optimistic lock plug-in:
@EnableTransactionManagement //Automatically manage transactions @Configuration @MapperScan("Modify as needed") public class MybatisPlusConfig { /** * Old edition */ @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } /** * new edition */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return mybatisPlusInterceptor; } }
7. Paging query:
7.1 paging configuration:
@EnableTransactionManagement //Automatically manage transactions @Configuration public class MybatisConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor () { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); //Optimistic lock configuration plug-in optisticlockerinnerinterceptor interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // Latest PaginationInnerInterceptor interceptor.addInnerInterceptor (new PaginationInnerInterceptor (DbType.H2)); return interceptor; } }
7.2 test:
//paging @Test public void testPage(){ //Parameter 1: current page parameter 2: page size Page<User> page = new Page<> (1,5); // page.getPages ();// Get total pages // page.getCurrent ();// Get current page // long size = page.getSize ();// Number of live pages Page<User> userPage = userMapper.selectPage (page, null); long pages = userPage.getPages (); for (User record : page.getRecords ()) { System.out.println (record); } System.out.println (pages); // System.out.println (size); }
8. Logical deletion:
- Logical deletion: false deletion, but can't be found later
- Physical deletion: really delete the data in the table
//delete physical data is directly removed; @Test public void testDelete(){ int i = userMapper.deleteById (1461235673628418052L); }
8.1 add the deleted field;
Some don't need to be added too much;
alter table user add column deleted boolean;
8.2 add @ TableLogic annotation to entity class field
@TableLogic private Integer deleted;
8.3 configuration
Method 1:
mybatis-plus: global-config: db-config: logic-delete-field: deleted # Global logically deleted entity field name (since 3.3.0, it can be ignored after configuration, and step 2 is not configured) logic-delete-value: 1 # Logical deleted value (default is 1) logic-not-delete-value: 0 # Logical undeleted value (0 by default)
Method 2: or configure on the configuration class:
@TableLogic private Integer deleted;
Configure in configuration class
/** * Logical delete plug-in * @return */ @Bean public ISqlInjector sqlInjector (){ return new LogicSqlInjector (); }
9.Wrapper:
9.1 QueryWrapper
Various methods:
isNotNull Not empty * ge Greater than or equal to * gt greater than * le Less than or equal to * lt less than * eq be equal to selectOne * * between and * * like Fuzzy query %..% * likeLeft %.. * likeRight ..% * notLike not %..% * inSql (age,"select id from user where id > 3") * age in ("select id from user where id > 3") * * * orderByDesc id Descending sort
@Test public void test1(){ //The query name is not empty, and the age is less than or equal to 20 QueryWrapper<User> wrapper = new QueryWrapper<> (); wrapper.isNotNull ("name"); wrapper.le ("age",20); List<User> list = userMapper.selectList (wrapper); for (User user : list) { System.out.println (list); } }
9.2 updateWrapper:
@Test public void testUpdate1() { //Modify value User user = new User(); user.setAge(99); user.setName("Andy"); //modify condition UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>(); userUpdateWrapper .like("name", "h") .or() .between("age", 20, 30); int result = userMapper.update(user, userUpdateWrapper); System.out.println(result);
UPDATE user SET name=?, age=?, update_time=? WHERE deleted=0 AND name LIKE ? OR age BETWEEN ? AND ?
10. Code generator:
public class CodeGenerator { @Test public void run() { // 1���������������� AutoGenerator mpg = new AutoGenerator(); // 2��ȫ������ GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir("D:\\JV\\Vaccine management\\project\\" + "/src/main/java"); //Remember to write the absolute path to the position of the birth scale gc.setAuthor("dl"); //author gc.setOpen(false); //���ɺ��Ƿ����Դ������ gc.setFileOverride(false); //��������ʱ�ļ��Ƿ� gc.setServiceName("%sService"); //ȥ��Service�ӿڵ�����ĸI gc.setIdType(IdType.ID_WORKER_STR); //�������� gc.setDateType(DateType.ONLY_DATE);//�������ɵ�ʵ�������������� gc.setSwagger2(true);//����Swagger2ģʽ mpg.setGlobalConfig(gc); // 3������Դ���� DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/yimiao?serverTimezone=GMT%2B8 "); / / database link url dsc.setDriverName("com.mysql.cj.jdbc.Driver"); //driver dsc.setUsername(""); //Database name root dsc.setPassword(""); // Database password dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); // 4�������� PackageConfig pc = new PackageConfig(); pc.setModuleName("app"); //ģ���� pc.setParent("com.dl"); //Package name pc.setController("controller"); pc.setEntity("entity"); pc.setService("service"); pc.setMapper("mapper"); mpg.setPackageInfo(pc); // 5���������� StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("address","administrators","appointment","logs","users","vaccines"); //The name of each table in the database strategy.setNaming(NamingStrategy.underline_to_camel);//��� ݿ �� ӳ And ʵ ����������� strategy.setTablePrefix(pc.getModuleName() + "_"); //����ʵ��ʱȥ����ǰ strategy.setColumnNaming(NamingStrategy.underline_to_camel);//��� ݿ ��� ֶ � ӳ And ʵ ����������� strategy.setEntityLombokModel(true); // lombok ģ�� @Accessors(chain = true) setter��ʽ���� strategy.setRestControllerStyle(true); //restful api�������� strategy.setControllerMappingHyphenStyle(true); //url���շ�ת���ַ� mpg.setStrategy(strategy); // 6��ִ�� mpg.execute(); } }
last:
Remember to pay attention!