Java development and learning----MyBatisPlus standard data layer (addition, deletion, search, modification and paging) development

1. Use of standard CRUD

What are the standard CRUD functions and what methods are provided by MyBatisPlus?

Let's look at a picture first:

1.1 Environment Preparation

The environment used here is Java development learning (forty) ---- MyBatisPlus entry case and introduction environment used in

2. Adding

Before adding new ones, we can analyze the new methods:

int insert (T t)
  • T: generic, new to save new data

  • int: return value, 1 is returned after the addition is successful, and 0 is returned if no addition is successful

Add new operations to the test class:

@SpringBootTest
class Mybatisplus01QuickstartApplicationTests {
​
    @Autowired
    private UserDao userDao;
​
    @Test
    void testSave() {
        User user = new User();
        user.setName("dark horse programmer");
        user.setPassword("itheima");
        user.setAge(12);
        user.setTel("4006184000");
        userDao.insert(user);
    }
}

After the test is executed, a data entry is added to the database table.

But the primary key ID in the data is a bit long, so how does this primary key ID come from? What we want more is that the primary key is incremented automatically, which should be 5. This is the primary key ID generation strategy we will introduce later. Let's put this issue aside for now.

3. Delete

Before deleting, we can analyze the method of deletion:

int deleteById (Serializable id)
  • Serializable: parameter type

    • Thinking: Why is the parameter type a serialization class?

      As can be seen from this figure,

      • String and Number are subclasses of Serializable,

      • Number is the parent class of Float,Double,Integer, etc.

      • The data types that can be used as primary keys are already subclasses of Serializable.

      • MyBatisPlus uses Serializable as parameter type, just like we can receive any data type with Object.

  • int: Return value type, 1 is returned if the data is deleted successfully, and 0 is returned if the data is not deleted.

Add new operations to the test class:

 @SpringBootTest
class Mybatisplus01QuickstartApplicationTests {
​
    @Autowired
    private UserDao userDao;
​
    @Test
    void testDelete() {
        // Pass in the primary key id
        userDao.deleteById(1401856123725713409L);
    }
}
​

4. Modification

Before making modifications, we can analyze the modified method:

int updateById(T t);
  • T: Generic, the data content that needs to be modified, note that because it is modified according to the ID, the incoming object needs to have the ID attribute value

  • int: return value, return 1 after successful modification, return 0 for unmodified data

Add new operations to the test class:

@SpringBootTest
class Mybatisplus01QuickstartApplicationTests {
​
    @Autowired
    private UserDao userDao;
​
    @Test
    void testUpdate() {
        User user = new User();
        user.setId(1L);
        user.setName("Tom888");
        user.setPassword("tom888");
        userDao.updateById(user);
    }
}

Description: When modifying, only modify the fields with values ​​in the entity object.

5. Query according to ID

Before querying by ID, we can analyze the method of querying by ID:

T selectById (Serializable id)
  • Serializable: parameter type, value of primary key ID

  • T: Querying by ID will only return one piece of data

Add new operations to the test class:

@SpringBootTest
class Mybatisplus01QuickstartApplicationTests {
​
    @Autowired
    private UserDao userDao;
    
    @Test
    void testGetById() {
        User user = userDao.selectById(2L);
        System.out.println(user);
    }
}

6. Query all

Before querying all, we can analyze and query all methods:

List<T> selectList(Wrapper<T> queryWrapper)
  • Wrapper: The condition used to construct the conditional query. At present, we do not have a direct pass as Null

  • List<T>: Because the query is all, the returned data is a collection

Add new operations to the test class:

@SpringBootTest
class Mybatisplus01QuickstartApplicationTests {
​
    @Autowired
    private UserDao userDao;
    
    @Test
    void testGetAll() {
        List<User> userList = userDao.selectList(null);
        System.out.println(userList);
    }
}

7. Lombok

When the code is written here, we will find that the writing of the DAO interface class is now the easiest, and nothing needs to be written in it. In turn, look at what is needed to write the model class:

  • private property

  • setter...getter...methods

  • toString method

  • Constructor

Although these contents are not difficult, and they are all generated by IDEA tools, the process still has to go through, so is there any optimization method for the writing of model classes? This is our next Lombok.

concept

  • Lombok, a Java class library, provides a set of annotations to simplify POJO entity class development.

Steps for usage

Step 1: Add lombok dependencies
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <!--<version>1.18.12</version>-->
</dependency>

Note: The version does not need to be written, because the version of lombok is already managed in SpringBoot.

Step 2: Install Lombok's plugin

The new version of IDEA has built-in this plug-in. If you delete the setter and getter methods, you need to install the plug-in.

If you can't find the lombok plugin in IDEA, you can visit the following website

https://plugins.jetbrains.com/plugin/6317-lombok/versions

Download the corresponding lombok plug-in according to your IDEA version. After the download is successful, install it in IDEA by offline installation.

Step 3: Add annotations to the model class

Common Lombok annotations are:

  • @Setter: Provides setter methods for properties of model classes

  • @Getter: Provides getter methods for properties of model classes

  • @ToString: Provides a toString method for the properties of the model class

  • @EqualsAndHashCode: Provides equals and hashcode methods for attributes of model classes

  • @Data: is a combined annotation that contains the functions of the above annotations

  • @NoArgsConstructor: Provides a no-argument constructor

  • @AllArgsConstructor: Provides a constructor with all arguments

There are many more annotations of Lombok, the three marked in red are more commonly used.

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private String password;
    private Integer age;
    private String tel;
}

illustrate:

Lombok just simplifies the writing of model classes, and our previous methods can also be used. For example, some people will ask: If I only want to have a constructor with name and password, how should I write it?

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private String password;
    private Integer age;
    private String tel;
​
    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }
}

This way is allowed.

Eight, paging function

The method used by the pagination query is:

IPage<T> selectPage(IPage<T> page, Wrapper<T> queryWrapper)
  • IPage: used to build paging query conditions

  • Wrapper: The condition used to construct the conditional query. At present, we do not have a direct pass as Null

  • IPage: return value, you will find that the return value of the construction paging condition and method is IPage

IPage is an interface, we need to find its implementation class to build it. For the specific implementation class, you can enter the IPage class and press ctrl+h, and you will find that it has an implementation class called Page.

Step 1: Call the method to pass in parameters to get the return value

@SpringBootTest
class Mybatisplus01QuickstartApplicationTests {
​
    @Autowired
    private UserDao userDao;
    
    //Paging query
    @Test
    void testSelectPage(){
        //1 Create an IPage paging object, set the paging parameters, 1 is the current page number, 3 is the number of records displayed on each page
        IPage<User> page=new Page<>(1,3);
        //2 Execute paging query
        userDao.selectPage(page,null);
        //3 Get paginated results
        System.out.println("Current page number value:"+page.getCurrent());
        System.out.println("Displays per page:"+page.getSize());
        System.out.println("How many pages in total:"+page.getPages());
        System.out.println("How many pieces of data in total:"+page.getTotal());
        System.out.println("data:"+page.getRecords());
    }
}

Step 2: Set up paging blocker

This interceptor MyBatisPlus has been provided for us, we only need to configure it as a Spring-managed bean object.

@Configuration
public class MybatisPlusConfig {
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        //1 Create MybatisPlusInterceptor interceptor object
        MybatisPlusInterceptor mpInterceptor=new MybatisPlusInterceptor();
        //2 Add paging blocker
        mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mpInterceptor;
    }
}

Explanation: What should I do if I can't remember the above code?

These contents are described in detail in the official documentation, we can view the official document class configuration

Step 3: Run the Test Program

If you want to view the SQL statement executed by MybatisPlus, you can modify the application.yml configuration file,

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #print SQL log to console

After opening the log, you can print out the corresponding SQL statement on the console, and the performance of the log function will be affected. Remember to close it after debugging.

 

Posted by HERATHEIM on Sun, 13 Nov 2022 17:41:48 +0300