mybatisPlus Advanced

Introduction to primary key generation strategy

  • Primary key: In a database, a primary key is often used to quickly find and access data. A primary key is a column or set of columns in a database table that uniquely identifies each row of data in the table. The primary key must be unique, and the primary key value cannot be NULL . Primary keys can be used to ensure data integrity and consistency , and can also be used to establish relationships between tables.
  • An annotation is provided in MybatisPlus, yes @TableId, the annotation provides various primary key generation strategies, and the primary key generation strategy is specified for the newly added data by using this annotation. When new data is added, the data will generate the corresponding primary key according to the specified primary key generation strategy.

AUTO strategy

  • This strategy follows the primary key increment strategy of the database table
  • When using the AUTO strategy (automatic increment) to generate the primary key value, the type of the database primary key should be set to an integer type (such as INT, BIGINT, etc.), so that it can be automatically incremented and ensure uniqueness. This is because an auto-incrementing primary key automatically generates a unique integer value for each newly inserted row, and integer types can store and process these values ​​more efficiently.
  • The premise is that the primary key of the database table should be set to self-increment, and the next increment number should be set here
    insert image description here
    insert image description here
  • Add annotations to the entity class and specify the primary key generation strategy
    @TableId(type = IdType.AUTO)
    private Long id;

INPUT strategy

  • For the INPUT strategy, the type of the database primary key can be any suitable data type, which is determined according to specific requirements.
  • The INPUT strategy means that the value of the primary key is manually entered or provided by the user, rather than automatically generated by the database. Therefore, the primary key can be any legal data type, such as integer, string, date, etc., depending on the business requirements and the characteristics of the data. It should be noted that it is necessary to ensure that the value of the primary key is unique in the table to maintain data integrity and consistency.
    @TableId(type = IdType.INPUT)
    private Long id;

ASSIGN_ID strategy

  • The ASSIGN_ID strategy is a strategy for manually assigning primary key values . The type of the primary key can be any suitable data type, which is determined according to specific requirements.
  • If no type value is set, the default IdType.ASSIGN_IDpolicy is used (since 3.3.0 3.3.03.3.0 onwards). MySQLThis strategy will use the snowflake algorithm to automatically generate the primary key ID, and the primary key type is long or string (the corresponding table fields areBIGINTandrespectivelyVARCHAR)
  • It should be noted that it is necessary to ensure that the value of the primary key is unique in the table to maintain data integrity and consistency.

  • The snowflake algorithm is composed of a 64-bit binary, which is ultimately a value of type Long . It is mainly divided into four parts of storage:
    1. The sign bit of the bit, the fixed value is 0
    2. 41-bit timestamp
    3. 10-digit machine code, including 5-digit machine id and 5-digit service id
    4. 12 digit serial number
      insert image description here
 @TableId(type = IdType.ASSIGN_ID)
 private Long id;

ASSIGN_UUID policy

  • UUID (Universally Unique Identifier) ​​is a globally unique identifier, defined as a string primary key, composed of 32-digit numbers, encoded in hexadecimal, and defines system information that is completely unique in time and space.
  • Encoding rules for UUID:
    1. 1~8 digits adopt the system time, and the system time is accurate to the millisecond level to ensure the uniqueness of the time;
    2. The 9~16 digits adopt the underlying IP address, which is unique in the server cluster;
    3. The 17~24 bits adopt the HashCode value of the current object, which is unique on an internal object;
    4. The 25~32 bits use a random number for calling the method, which is unique at the millisecond level within an object.
  • When using UUID as the MySQL primary key, the primary key type should be selected VARCHAR. UUID is a 36-bit string consisting of 32 hexadecimal digits and 4 hyphens. Therefore, you need to use VARCHAR(36)to store the UUID.
  @TableId(type = IdType.ASSIGN_UUID)
  private String id;

NONE strategy

  • The NONE strategy means that no primary key generation strategy is specified. When we do not specify a primary key generation strategy or the primary key strategy is NONE, the global strategy follows. The global default configuration id-typeuses the snowflake algorithm.
 @TableId(type = IdType.NONE)
 private Long id;

MybatisPlus pagination

paging plugin

  • The essence of paging is to set up an interceptor, intercept the SQL through the interceptor, and realize the effect of paging by adding the limit keyword at the end of the SQL statement.

  • configuration steps

  1. Specify the paging plug-in of a specific database through the configuration class, because different databases have different dialects, and the specific generated paging statements will also be different.
@Configuration
public class MybatisPlusConfig {
    
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
    
    
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
  1. Realize pagination query effect
@Test
void selectPage(){
    
    
    //1.创建QueryWrapper对象
    LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    //2.创建分页查询对象,指定当前页和每页显示条数
    IPage<User> page = new Page<>(1,3);
    //3.执行分页查询
    userMapper.selectPage(page, lambdaQueryWrapper);
    //4.查看分页查询的结果
    System.out.println("当前页码值:"+page.getCurrent());
    System.out.println("每页显示数:"+page.getSize());
    System.out.println("总页数:"+page.getPages());
    System.out.println("总条数:"+page.getTotal());
    System.out.println("当前页数据:"+page.getRecords());
}
  1. Query statement view
    insert image description here

Custom pagination plugin

In some scenarios, custom SQL statements are required for querying. Next, demonstrate the paging operation of custom SQL

  1. Provide the query statement in UserMapper.xmlthe mapping configuration file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.powernode.mapper.UserMapper">
     <select id="selectByName" resultType="com.powernode.domain.User">
        select * from powershop_user where name = #{name}
     </select>
</mapper>
  1. MapperThe corresponding method is provided in the interface, and the object is passed in as a parameter in the IPagemethod
@Mapper
public interface UserMapper extends BaseMapper<User> {
    
    
       IPage<User> selectByName(IPage<User> page, String name);
}
  1. Realize pagination query effect
@Test
void selectPage2(){
    
    
    //1.创建分页查询对象,指定当前页和每页显示条数
    IPage<User> page = new Page<>(1,2);
    //2.执行分页查询
    userMapper.selectByName(page,"Mary");
    //3.查看分页查询的结果
    System.out.println("当前页码值:"+page.getCurrent());
    System.out.println("每页显示数:"+page.getSize());
    System.out.println("总页数:"+page.getPages());
    System.out.println("总条数:"+page.getTotal());
    System.out.println("当前页数据:"+page.getRecords());
}

ActiveRecord mode

  • ActiveRecord (Active Record, referred to as AR), is a domain model pattern, characterized in that a model class corresponds to a table in a relational database, and an instance of the model class corresponds to a row of records in the table.
  • ActiveRecord has been widely loved by interpreted dynamic languages ​​(PHP, Ruby, etc.), by performing CRUD operations around a data object. As a quasi-static (compiled) language, Java can only admire its elegance for ActiveRecord, so MP has also carried out some exploration on the road of AR. It only needs to let the entity class inherit the Model class and implement the method of specifying the primary key to open it. AR tour.

  • Implementation steps
  1. Let the entity class inherit the Model class
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User extends Model<User> {
          
          
        private Long id;
        private String name;
        private Integer age;
        private String email;
    }
    
    • The Model class provides some CRUD methods, which can be directly called by entity class objects, which simplifies the syntax of the operation, but the bottom layer still needs UserMapper, so the persistence layer interface cannot be omitted
  2. Test the addition, deletion, modification and query of ActiveRecord mode
    • adding data
    @Test
    void activeRecordAdd(){
          
          
        User user = new User();
        user.setName("wang");
        user.setAge(35);
        user.setEmail("[email protected]");
        user.insert();
    }
    
    • delete data
    @Test
    void activeRecordDelete(){
          
          
        User user = new User();
        user.setId(8L);
        user.deleteById();
    }
    
    • change the data
    @Test
    void activeRecordUpdate(){
          
          
        User user = new User();
        user.setId(6L);
        user.setAge(50);
        user.updateById();
    }
    
    • Query data
    @Test
    void activeRecordSelect(){
          
          
        User user = new User();
        user.setId(6L);
        User result = user.selectById();
        System.out.println(result);
    }
    

SimpleQuery tool class

Introduction to SimpleQuery

  • SimpleQuery can encapsulate the result of selectList query with Stream, so that it can return some specified results, which simplifies the call of API

list

  • Demonstrates field-based encapsulation of collections
@Test
void testList(){
    
    
   //.list()方法执行查询,并返回符合条件的用户列表
   //使用.list(User::getId)来指定返回的字段为ID
    List<Long> ids = SimpleQuery.list(new LambdaQueryWrapper<User>().eq(User::getName, "Mary"), User::getId);
    System.out.println(ids);
}
  • Demonstrates lambda operations on encapsulated fields
@Test
void testList2(){
    
    
    /* e ->  Optional.of(e.getName()).map(String::toLowerCase).ifPresent(e::setName)
      额外的逻辑处理,即对返回的姓名进行转换
      Optional.of(e.getName())用于将姓名转换为Optional对象,以便进行后续的操作。
      接着,.map(String::toLowerCase)将姓名转换为小写形式。最后,.ifPresent(e::setName)将转换后的小写姓名设置回User对象的姓名属性。
    */
    List<String> names = SimpleQuery.list(new LambdaQueryWrapper<User>().eq(User::getName, "Mary"),User::getName,e ->  Optional.of(e.getName()).map(String::toLowerCase).ifPresent(e::setName));
    System.out.println(names);
}

map

  • Demonstrate that all objects are encapsulated as a Map collection in the form of id and entity
@Test
void testMap(){
    
    
    //将所有元素封装为Map形式
    Map<Long, User> idEntityMap = SimpleQuery.keyMap(new LambdaQueryWrapper<>(), User::getId);
    System.out.println(idEntityMap);
}
  • Demonstrate the encapsulation of a single object as a Map collection in the form of id and entity
@Test
void testMap2(){
    
    
    //将单个元素封装为Map形式
    Map<Long, User> idEntityMap = SimpleQuery.keyMap(
            new LambdaQueryWrapper<User>().eq(User::getId,1L), User::getId);
    System.out.println(idEntityMap);
}
  • The demo only wants a map composed of id and name
@Test
void testMap3(){
    
    
    //只想要只想要id和name组成的map
    Map<Long, String> idNameMap = SimpleQuery.map(new LambdaQueryWrapper<>(), User::getId, User::getName);
    System.out.println(idNameMap);
}

Group

  • Demo grouping effect
@Test
void testGroup(){
    
    
    Map<String, List<User>> nameUsersMap = SimpleQuery.group(new LambdaQueryWrapper<>(), User::getName);
    System.out.println(nameUsersMap);
}

Guess you like

Origin blog.csdn.net/yang2330648064/article/details/131993212