MybatisPlus Usage Summary 2021-09-22

Mybatis application

1 Introduction to Mybatis and coding process
2 mapper agent development method
3 Global profile
4 Input mapping and output mapping
5 Association query
6 Delayed loading
7 Dynamic SQL
8 Mybatis cache

Extended content

1 MybatisPlus Usage Summary
2 MyBatis Plus learning documentation
3 JDBC content review
4 Mybatis source code analysis

1, Introduction

MyBatis-Plus (MP) is a MyBatis On the basis of MyBatis, the enhancement tool is only enhanced without change. It is born to simplify development and improve efficiency.

The steps are as follows:

1.1 edit pom.xml file to add related dependencies

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.1.1</version>
</dependency>

[note] after introducing MyBatis plus, please do not introduce MyBatis and MyBatis spring again to avoid problems caused by version differences.

1.2 relevant configuration

1. application.yml file
Edit the application.yml configuration file, mainly to add the related configuration of druid database
2. Add the @ MapperScan annotation in the Spring Boot startup class to scan the Mapper folder

@SpringBootApplication
@MapperScan("com.kkb.mapper")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(QuickStartApplication.class, args);
    }

}

[note] if it is a spring MVC project, you need to configure MapperScan in the < bean > tab.

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.kkb.mapper"/>
</bean>

Then you can also adjust the SqlSessionFactory to the SqlSessionFactory of mybatis plus.

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
</bean>

1.3 create corresponding classes

New User class
New UserMapper mapping interface class

Examples of usage:

@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1 {

    @Autowired
    private UserMapper userMapper;

    @Test
	public void testSelect(){
		
		// null here means that you do not need to query according to parameters
		// You can call CRUD in a variety of ways

		// 1. Query all data
		List<User> userList = userMapper.selectList(null);
		userList.forEach(user -> System.out.println(user.getName()));
		
		// 2. Delete by id
		userMapper.deleteById(1);
		
		// 3. Add data
		User user = new User();
		user.setName("Lao Wang");
		user.setEmail("laowang@kkb.com");
		user.setAge(18);
		userMapper.insert(user);
		
		// 4. Update data
		user.setName("Lao Wang Wang");
		user.setEmail("laowangwang@kkb.com");
		userMapper.updateById(user);
	}
    
}

1.4 common notes

  1. @TableName: table name Description
  2. @TableId: primary key comment
  3. @TableField: field annotation (non primary key)
  4. @Version: optimistic lock annotation, which is mainly used to mark on the field
  5. @EnumValue: General enumeration class annotation (annotation on enumeration field)
  6. @TableLogic: table field logical processing annotation (logical deletion)
  7. @SqlParser: Tenant annotation (annotation on mapper is supported)
  8. @KeySequence: sequence primary key policy. The attributes are value and resultMap

2, CRUD interface

2.1 Mapper CRUD interface

  • Universal CRUD package BaseMapper Interface, which automatically resolves entity table relationship mapping when Mybatis plus is started, and transforms it into Mybatis internal object injection container
  • Generic T is any entity object
  • The parameter Serializable is any type of primary key. Mybatis plus does not recommend using the compound primary key convention. Each table has its own unique id primary key
  • Object Wrapper is Conditional constructor
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo {
	
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect(){

        // 1. Add data (make sure that the primary key of the table is in auto increment status)
        User user = new User();
        user.setName("Lao Wang");
        user.setEmail("laowang@kkb.com");
        user.setAge(18);
        userMapper.insert(user);

        // 2. Delete by id
        userMapper.deleteById(6);

        // 3. Delete the record according to the columnMap condition
        // Maps belongs to the com.google.common.collect.Maps package and comes from Guava
        // Guava means pomegranate in Chinese. This project is an open source project of Google and contains many common Java libraries of Google core
        Map<String, Object> columnMap = Maps.newHashMap();
        columnMap.put("id", 3);

        userMapper.deleteByMap(columnMap);

        // 4. Query all data
        // Pass null directly without specifying conditions
        List<User> userList = userMapper.selectList(null);
        userList.forEach(user -> System.out.println("User:" + user));

        // 5. Batch query
        List<String> idList = new ArrayList<String>();
        idList.add("1");
        idList.add("2");
        List<User> userList = userMapper.selectBatchIds(idList);
        userList.forEach(user -> System.out.println("User:" + user));

    }
}

2.2 Service CRUD interface

  • Universal Service CRUD encapsulation IService Interface to further encapsulate CRUD. get query single line remove delete list query set page page prefix naming method is used to distinguish Mapper layer to avoid confusion.
  • Generic T is any entity object
  • It is recommended that if it is possible to customize the general Service method, please create your own IBaseService to inherit the base class provided by mybatis plus
  • Object Wrapper is Conditional constructor

3, Conditional constructor

  • The following first parameter boolean condition indicates whether the condition is added to the last generated sql

3.1 AbstractWrapper

Parent classes of QueryWrapper(LambdaQueryWrapper) and UpdateWrapper(LambdaUpdateWrapper)
The where condition is used to generate sql, and the entity attribute is also used to generate the where condition of sql

Note: the where condition generated by entity does not have any associated behavior with the where condition generated using various APIs.

3.2 SelectWrapper

3.3 UpdateWrapper

Keywords: Java Spring Spring Boot

Added by scraff on Sat, 25 Sep 2021 08:22:28 +0300