Dependencies and configuration

Use the following SQL to create the database and add data

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));DELETE FROM user;

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]');
Copy the code

1. Create a SpringBoot project in IDEA and add the required dependencies to POM.xml

Add MyBatis-Plus, mysql connection driver, Lombok dependencies

<dependency>
    <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.0.5</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>
Copy the code

2. Configure the database connection

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mp
    username: root
    password: 1234
Copy the code

Add the annotation @mapperscan to the startup class to scan the Mapper interface package

@SpringBootApplication
@MapperScan("com.jikedaquan.study.mp.mapper")
public class MpApplication {

    public static void main(String[] args) { SpringApplication.run(MpApplication.class, args); }}Copy the code

Write entity classes, using Lombok

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
Copy the code

5. Write UserMapper interface

The UserMapper interface inherits the BaseMapper interface provided by MyBatis-Plus to have CRUD methods. The entity class of the operation is filled in the generic type, which is User here

public interface UserMapper extends BaseMapper<User> {}Copy the code

6. Test query data

@RunWith(SpringRunner.class)
@SpringBootTest
public class MpApplicationTests {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void contextLoads(a) {
        List<User> userList = userMapper.selectList(null);// Query all data when the condition is nulluserList.forEach(System.out::println); }}Copy the code

2. Log configuration

Configure log output to the console

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Copy the code

Primary key generation strategy

MyBatis-Plus provides a variety of primary key generation strategies for different scenarios

strategy instructions
AUTO The database ID is automatically increased
NONE The primary key type is not set
INPUT The user enters an ID, which can be filled by registering the autofill plug-in themselves
ID_WORKER Globally unique ID (idWorker)
UUID Globally unique ID (UUID)
ID_WORKER_STR String globally unique ID (string representation of idWorker)

Annotations control the primary key generation strategy

Add an annotation to the primary key field of the entity class.

@Data
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
Copy the code

2. Global configuration controls primary key generation policies

application.yml

mybatis-plus:
  global-config:
    db-config:
      id-type: id_worker
Copy the code

Iv. Automatic filling

Some attributes in common services need to be configured with some default values. MyBatis-Plus provides plug-ins to achieve this function. Modify the user table here by adding create_time and update_time fields, and add corresponding attributes to the user class.

1. Add the @tableField annotation for the attributes that need to be filled automatically

Four automatic fill policies are provided: DEFAULT, which does not process by DEFAULT. INSERT, INSERT the fill field. UPDATE: Updates the fill field. INSERT_UPDATE, inserts and updates the fill field.

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;

    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}
Copy the code

2. Realize the field filling controller and write custom filling rules

MetaObjectHandler interface, insertFill and updateFill methods, where create_time and update_time fields need to be filled when inserted, only update_time fields need to be filled when modified. So here’s the strategy.

// The custom fill controller needs to be registered as a component
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final Logger LOGGER= LoggerFactory.getLogger(MyMetaObjectHandler.class);

    // The field to fill in the insert operation
    @Override
    public void insertFill(MetaObject metaObject) {
        LOGGER.info("start insert fill ...");
        // Set the value to be filled according to the property name
        this.setFieldValByName("createTime".new Date(),metaObject);
        this.setFieldValByName("updateTime".new Date(),metaObject);
    }

    // Fields to fill in during the update operation
    @Override
    public void updateFill(MetaObject metaObject) {
        LOGGER.info("start insert fill ...");
        this.setFieldValByName("updateTime".newDate(),metaObject); }}Copy the code

3. Insert data test

@RunWith(SpringRunner.class)
@SpringBootTest
public class CRUDTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testInsert(a){
        User user = new User();
        user.setName("jack11");
        user.setAge(20);
        user.setEmail("[email protected]");

        intresult= userMapper.insert(user); System.out.println(result); System.out.println(user); }}Copy the code

4. Modify data tests

@Test
public void testUpdate(a){
    User user = new User();
    user.setId(2L);
    user.setName("Jackie");
    int result = userMapper.updateById(user);
    System.out.println(result);
}
Copy the code

After an insert, create_time and update_time are filled with the set time. After the update operation, only update_time is filled with the set time.

Optimistic lock plug-in

The core principle of optimistic locking is that the commit version must be equal to the record of the current version before an update can be performed

Intentions:

  • When a record is updated, it is hoped that the record has not been updated by others

Optimistic lock implementation:

  • When the record is fetched, the current version is retrieved
  • When you update, take this version with you
  • When performing an update, set version = newVersion where version = oldVersion
  • If the version is incorrect, the update fails

1. Add version to tables and classes, and add @Version annotations to properties

@Version
private Integer version;
Copy the code

2. Configure the plug-in

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(a){
        return newOptimisticLockerInterceptor(); }}Copy the code

3. Test two cases of modification

@Test
public void testOptimisticLocker1(a) {
    User user = userMapper.selectById(1128212430124097543L);
    user.setName("After modification");
    int result = userMapper.updateById(user);
    if (result == 1) {
        System.out.println("Modified successfully");
    } else {
        System.out.println("Modification failed"); }}@Test
public void testOptimisticLocker2(a) {
    User user = userMapper.selectById(1128212430124097543L);
    user.setName("After modification");
    user.setVersion(user.getVersion()-1);// Test the old version
    int result = userMapper.updateById(user);
    if (result == 1) {
        System.out.println("Modified successfully");
    } else {
        System.out.println("Modification failed"); }}Copy the code

6. Paging plug-ins

Enabling the paging plug-in and enabling the optimistic lock plug-in are both done by registering a Bean

1. Enable the paging plug-in

@Bean
public PaginationInterceptor paginationInterceptor(a){
    return new PaginationInterceptor();
}
Copy the code

2, test paging query

@Test
public void testSelectPage(a){
    // Build the second page to display 3 pages per page
    Page<User> page=new Page<>(2.3);
    // Use paging condition query, no other condition
    userMapper.selectPage(page, null);
    // Get the records queried after paging
    List<User> records = page.getRecords();
    records.forEach(System.out::println);
    System.out.println("Is there a next page?"+page.hasNext());
    System.out.println("Is there a previous page:"+page.hasPrevious());
    System.out.println("Total records:"+page.getTotal());
}
Copy the code

Logical delete plugin

Logical deletion can be used when data that you want to no longer display is still physically present. Logical deletion refers to adding a logical field to the table (a field deleted is added). The actual deletion operation is to operate this logical value and perform further operations based on this logical value during query and modification.

1. Enable the logical delete plug-in

@Bean
public LogicSqlInjector logicSqlInjector(a){
    return new LogicSqlInjector();
}
Copy the code

2. Add the logical mapping configuration

mybatis-plus:
  global-config:
    db-config:
      logic-delete-value: 1 # Logical deleted value (default: 1)
      logic-not-delete-value: 0 # Logical undeleted value (default: 0)
Copy the code

3. Add @tablelogic annotation to logical fields

@TableLogic
private Integer deleted;
Copy the code

4. Test logic deletion

@Test
public void testLogicDelete(a){
    int result=userMapper.deleteById(1L);
    System.out.println(result);
}
Copy the code

Looking at the log, you can see that the SQL generated is an UPDATE statement

Performance analysis plug-in

Observe SQL execution time during development and testing

1. Configure SpringBoot as the development environment

spring:
  profiles:
    active: dev
Copy the code

2. Enable the plug-in

@Bean
@Profile({"dev"."test"}) // Enable the dev test environment
public PerformanceInterceptor performanceInterceptor(a){
    return new PerformanceInterceptor();
}
Copy the code

Ix. CRUD Other operations

@Test
public void testSelectById(a) {
    User user = userMapper.selectById(1L);
    System.out.println(user);
}

@Test
public void testSelectBatchIds(a) {
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1.2.3));
    users.forEach(System.out::println);
}

@Test
public void testSelectByMap(a) {
    Map<String, Object> param = new HashMap<>();
    param.put("name"."jack");
    param.put("age".18);
    List<User> users = userMapper.selectByMap(param);
    users.forEach(System.out::println);
}

@Test
public void testSelectMap(a){
    Page<User> page = new Page<>(2.3);
    IPage<Map<String, Object>> mapIPage = userMapper.selectMapsPage(page, null);
}

@Test
public void testDeleteById(a){
    int result = userMapper.deleteById(1L);
    System.out.println(result);
}

@Test
public void testDeleteBatchIds(a){
    int result = userMapper.deleteBatchIds(Arrays.asList(2L.3L.4L));
    System.out.println(result);
}
Copy the code

Welcome those who love technology to communicate with me