Quick start
-
Create database mybatis-plus
-
Create table
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT 'primary key ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT 'name',
age INT(11) NULL DEFAULT NULL COMMENT 'age',
email VARCHAR(50) NULL DEFAULT NULL COMMENT 'email'.PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1.'Jone'.18.'[email protected]'),
(2.'Jack'.20.'[email protected]'),
(3.'Tom'.28.'[email protected]'),
(4.'Sandy'.21.'[email protected]'),
(5.'Billie'.24.'[email protected]');
-- In real development, version (optimistic lock), deleted (logical deletion), gmT_create, gmt_Modified
Copy the code
- Initialize the project using SpringBoot
- Import dependence
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0. 5</version>
</dependency>
Copy the code
- Connect to the database! This step is the same as mybatis!
spring.datasource.username=root
spring.datasource.password=ccc+022599
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus? useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
Copy the code
- Write POJOs and Mapper
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
Copy the code
package cn.ccb.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import cn.ccb.pojo.User;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
// BaseMapper inherits all methods from its parent class
// All CRUD operations have been written
}
Copy the code
test
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads(a) {
// The argument is a Wrapper, conditional constructor, we don't need null here
// Query all users
List<User> users = userMapper.selectList(null); users.forEach(System.out::println); }}Copy the code
To configure the log
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
Copy the code
Primary key generation policy
-
@tableId on entity class field (type = idType.auto)
@TableId(type =IdType.AUTO )// Primary key policy private Long id; Copy the code
public enum IdType { AUTO(0), // The database ID is automatically increased NONE(1), // The primary key is not set ID_WORKER(3), // The default global unique ID UUID(4), // Globally unique ID UUID } Copy the code
-
The database primary key field must be self-increment
Automatic filling
- Add annotations to entity class field attributes
// Add padding to the field
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
Copy the code
- Write a processor to handle this annotation!
package cn.ccb.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
// Fill the policy when inserting
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime".new Date(),metaObject);
this.setFieldValByName("updateTime".new Date(),metaObject);
}
// Update the policy
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime".newDat(),metaObject); }}Copy the code
Test insert, update, and observe the time!
Optimistic locking
Implementation method:
- When the record is fetched, the current version is retrieved
- When performing an update, set version = newVersion where version = oldVersion
- If the version is incorrect, the update fails
Optimistic lock: Obtain the version number version =1
// Thread A completes an operation on A resource first, when version = 2
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1 // Version has changed to 2. Thread B fails
Copy the code
Test MP’s optimistic lock plugin
-
Add version field to database!
-
Entity class plus corresponding field
@Version // Optimistic lock Version annotation private Integer version; Copy the code
-
To register the plugin
@Configuration / / configuration class public class MyBatisPlusConfig { @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor(a) { return newOptimisticLockerInterceptor(); }}Copy the code
Logic to delete
Physical delete: Removes a logical delete from a database directly: invalidates a variable instead of removing it from the database! deleted = 0 => deleted = 1
Administrators can view deleted records! Prevent data loss!
- Add a deleted field to the data table
- Add attributes to the entity class
@TableLogic // Logical delete
private Integer deleted;
Copy the code
- configuration
// Remove the component logically
@Bean
public ISqlInjector iSqlInjector(a){
return new LogicSqlInjector();
}
Copy the code
# logical delete
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
Copy the code
- Remove front:
- To delete
- After deleting
The record is still in the database, but the value has changed!
Code generator
Dao, POJO, service and Controller are all written by me! 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 CodeGenerator {
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// Global configuration
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setOpen(false);
gc.setSwagger2(true); // Open swagger annotation
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
// Set the data source
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("ccc+022599");
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus? useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf-8");
mpg.setDataSource(dsc);
/ / package configuration
PackageConfig pc = new PackageConfig();
pc.setParent("cn.tony");
pc.setModuleName("student");
pc.setEntity("pojo");
mpg.setPackageInfo(pc);
// Policy configuration
StrategyConfig strategy = new StrategyConfig();
** strategy.setInclude("sys_teacher","sys_stu","user"); /** strategy.setInclude("sys_teacher","sys_stu","user"); Only these three tables are mapped */
strategy.setInclude();
/* If the table name and field name are underlined, the name is humped */
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setLogicDeleteFieldName("deleted");
// Auto-fill
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
/ / optimistic locking
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true); mpg.setStrategy(strategy); mpg.execute(); }}Copy the code