[MybatisPlus] MP solves the mapping problems between four tables and entities, as well as the id self-increment strategy

Preface

When there are too many CRUDs, a certain mindset is formed - the data fields obtained correspond to the attributes in the entity class one-to-one. This seems to be quite satisfactory and things should be done according to the rules. Do the fields in the table always correspond to the attributes in the class?
Insert image description here
The above is the so-called ideal situation, with fields and attributes corresponding one-to
-one. Let’s explore the first possible problem.

1. Fields and attribute values ​​are different

I changed the attributes in the entity class to see what results would be reported when executing an ordinary query.
Insert image description here
The query failed!
Therefore, when the column names of the table and the attribute names of the model class are inconsistent, the data will not be encapsulated in the model object. At this time, one of the parties needs to make changes. At this time, an annotation from MP helped us solve this problem. MP gave
us An annotation@TableField is provided , which can be used to realize the mapping relationship between the model class attribute name and the column name of the table, like this@TableField(value = "password")
Insert image description here

2. Attributes that do not exist in the table

When a field that does not exist in the database table appears in the entity class, it will cause the generated SQL statement to query the field that does not exist in the database when selecting. The specific solution still
Insert image description here
uses annotations, which have an attribute called , Set whether the field exists in the database table. If set to false, it does not exist. When generating a SQL statement query, the field will not be queried again.@TableFieldexist

3. Attributes that do not exist in the table

After the operation, some sensitive data may be queried and returned to the front end. At this time, we need to limit which fields should not be queried by default. According to common sense, private information such as passwords should not be queried together. How can we hide these fields? ? Or through the @TableField annotation:
Insert image description here
@TableFieldOne of the attributes of the annotation is calledselect. This attribute sets whether the value of the field needs to be queried by default. true (default value) means that the field is queried by default, and false means that the field is not queried by default.

name @TableField
type Property annotation
Location Above the model class attribute definition
effect Set the field relationship in the database table corresponding to the current attribute

value (default): Set the database table field name.
exist: Set whether the attribute exists in the database table field. The default is true. This attribute cannot be combined with value.
Select: Set whether the attribute participates in the query. This attribute is not configured with the select() mapping. conflict

4. Class name and table name do not match

I remember that Lazy Yangyang solved a bug some time ago:
Insert image description here
in short, the class name of the entity class was not consistent with the table name in the database, resulting in MP unable to be mapped and associated with the table . Unexpectedly, I learned that I can use annotations to solve the problem later:
MP provides another annotation @TableNameto set the corresponding relationship between tables and entity classes :
Insert image description here
In this way, I no longer have to deliberately write entity classes according to table names!

name @TableName
type Class annotation
Location Above the model class definition
effect Set the current class to correspond to the database table relationship
Related properties value (default): Set the database table name

5. ID self-increment strategy

1.type = IdType.AUTO

When I first started using MP, I wrote an adding method, but the strange thing is that the added data primary key ID does not increase sequentially, but a very strange number, like this: After the addition is successful, the primary key
Insert image description here
ID It is a very long string of content. What we want more is to auto-increment according to the database table fields, and different tables apply different ID generation strategies, such as: log: auto-increment (1, 2, 3, 4,...
)
Order: special rules (FQ77948AK3982)
takeaway order: related area date and other information (50 22 24765314 87 44)

Let’s take self-increment as an example: @TableId annotation
Insert image description here

name @TableId
type Property annotation
Location Above the attribute definition in the model class used to represent the primary key
effect Set the generation strategy for primary key attributes in the current class
Related properties value (default): Set the primary key name of the database table
type: Set the generation strategy of the primary key attribute, the value is based on the enumeration value of IdType

There are many strategies in the idType enumeration class:

@Getter
public enum IdType {
    
    
    /**
     * 数据库ID自增
     * <p>该类型请确保数据库设置了 ID自增 否则无效</p>
     */
    AUTO(0),
    /**
     * 该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
     */
    NONE(1),
    /**
     * 用户输入ID
     * <p>该类型可以通过自己注册自动填充插件进行填充</p>
     */
    INPUT(2),

    /* 以下2种类型、只有当插入对象ID 为空,才自动填充。 */
    /**
     * 分配ID (主键类型为number或string),
     * 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(雪花算法)
     *
     * @since 3.3.0
     */
    ASSIGN_ID(3),
    /**
     * 分配UUID (主键类型为 string)
     * 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(UUID.replace("-",""))
     */
    ASSIGN_UUID(4);

    private final int key;

    IdType(int key) {
    
    
        this.key = key;
    }
}

Next let’s look at another strategy

2.type = IdType.INPUT

Automatically populate by registering yourself
When turning off auto-increment in the database and using this strategy to perform an add operation:
@TableId(type = IdType.INPUT)

    @Test
    void testSave() {
    
    
        Users user = new Users();
        user.setName("暖羊羊");
        user.setPw("777");
        user.setAge(11);
        user.setTel("26262665");
        userDao.insert(user);
    }

Insert image description here
Obviously the data cannot be added. The id appears in the generated SQL but is not passed in to the method, so we need to fill it in ourselves:

    @Test
    void testSave() {
    
    
        Users user = new Users();
        user.setId(77L);
        user.setName("暖羊羊");
        user.setPw("777");
        user.setAge(11);
        user.setTel("26262665");
        userDao.insert(user);
    }

Finally, the addition was completed
Insert image description here

NONE Do not set id generation strategy
INPUT User manually enters ID
ASSIGN_ID Snowflake algorithm generates id (compatible with numeric and string types)
ASSIGN_UUID Using UUID generation algorithm as id generation strategy

I also looked up the pros and cons of various strategies:

  • NONE: No id generation strategy is set, and MP is not automatically generated, which is approximately equal to INPUT. Therefore, both methods require users to set it manually. However, the first problem with manual setting is that the same ID is prone to cause primary key conflicts. In order to ensure that primary keys do not conflict You need to make a lot of judgments, and it is more complicated to implement.
  • AUTO: The database ID is auto-incremented. This strategy is suitable for use when there is only one database server, and cannot be used as a distributed ID
  • ASSIGN_UUID: can be used in distributed situations and can guarantee uniqueness, but the generated primary key is a 32-bit string, which is too long and takes up space and cannot be sorted, and the query performance is also slow.
  • ASSIGN_ID: can be used in a distributed situation. It generates Long type numbers, which can be sorted and have high performance. However, the generated strategy is related to the server time. If the system time is modified, it may lead to duplicate primary keys.

3. Introduction to Snowflake Algorithm

Use a 64-bit long number as the globally unique ID. It is widely used in distributed systems, and ID introduces timestamps. Basically, the self-increasing
Insert image description here
snowflake algorithm is a 64-bit binary. Bit 1 is the sign bit, which is the highest bit, which is always 0, which has no meaning, because If the only computer two's complement is a negative number, 0 is a positive number. 41 bits is the timestamp, specific to milliseconds. The 41-bit binary can be used for 69 years. Because time theoretically increases forever, it is possible to sort according to this

4. Unify primary key strategy

In future projects, in order not to configure the primary key strategy of each entity class separately, we can set the gradual strategy in a unified manner, like this:

mybatis-plus:
  global-config:
    db-config:
    	id-type: assign_id

In this way, the configuration can be unified everywhere!

Guess you like

Origin blog.csdn.net/weixin_57535055/article/details/127036295