One 、 Primary key id Generation

Database tables usually have a primary key id, As the unique identifier of this data .

Common ways

  1. Automatic database growth

    This is very common , It can be unique in the whole database . because id It's natural , It is convenient for operations involving sorting .

  2. UUID

    The automatic growth above , Simple though , But for the operation of sub table, it is more troublesome . Because when you insert the data in the second one , You need to get the last data from the last table id.

    UUID Is different , A random unique value every time , But because it's random , So there's no sort .

  3. redis

    redis It can also be used to generate id, utilize redis Atomic operation of . The advantage is that you don't have to rely on the database , Good performance , But then because redis The introduction of , It brings a certain degree of complexity .

mybatis-plus The way

In fact, before the use of mp When adding new data , I didn't configure it , By default, it will have a primary key id.

It's also very simple to configure , Annotate the primary key ,@TableId(type = IdType.ID_WORKER)

public class User {
@TableId(type = IdType.ID_WORKER)
private Long id;
private String name;
private Integer age;
private String email; @TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) // When it's added update It's worth it
private Date updateTime;

stay idea In the editor , You can hold down the ctrl+ Left click , notice IdType Several enumeration values of .

  • AUTO: Is to use the database to increase
  • NONE: Not set , The value needs to be set manually
  • INPUT: The value needs to be set manually
  • UUID: Generate UUID Primary key of type id
  • ID_WORKER: Generate 19 The value of a , Numeric type
  • ID_WORKer_STR: Generate 19 The value of a , String type

About mp This 19 Generation of bit values , You can make an understanding of , Take advantage of snowflake Algorithm .

snowflake yes Twitter Open source distributed ID generating algorithm , The result is a long Type ID.

The central idea is this : Use 41bit As milliseconds ,10bit As a machine ID(5 individual bit It's the data center ,5 individual bit Machine ID),

12bit As a serial number in milliseconds ( It means that every node can produce 4096 individual ID), And finally, there's a sign bit , Forever 0.

Two 、mp Realize automatic filling

There is also a common operation when operating a database , It's just the filling of some fields , For example, the common create_time、update_time etc. , It's all filled in the same way .

So in addition to each manual fill , It can also automatically fill in . And in the MP Set auto fill in as long as 2 Step by step :

1. adding annotations

@TableField(fill = FieldFill.INSERT)@TableField(fill = FieldFill.INSERT_UPDATE).

public class User {
@TableId(type = IdType.ID_WORKER)
private Long id;
private String name;
private Integer age;
private String email; @TableField(fill = FieldFill.INSERT) // Fill in the data when adding new ones
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) // Fill in data when adding or modifying
private Date updateTime;

2. Custom implementation class MyMetaObjectHandler

Here we need to write an implementation class ourselves

@Component // This annotation indicates   Give it to spring To manage 
public class MyMetaObjectHandler implements MetaObjectHandler {
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
} @Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(), metaObject);

by the way , To add the corresponding field in the database table create_timeupdate_time. You can try it after adding it , First, add a new test data :

//     newly added 
void addUser() {
User user = new User();
user.setName(" Lao Wang ");

After successful execution, view the database table :

When it's added ,2 All the time fields are filled in .

Now when you only do the update operation , It's just going to update update_time.

//     modify 
void updateUser() {
User user = new User();
user.setName(" After Lao Wang's modification ");
userMapper.updateById(user); }

Results the correct .

【mybatis-plus】 Primary key id Generate 、 Field auto fill more related articles

  1. mybatis in the light of SQL Server Of Primary key id Generation strategy

    SQL Server In the command : select newId()  , You can get SQL server Database native UUID value , So we can write this instruction to Mybatis Primary key generation policy configuration of selectKey in . ...

  2. When opening a transaction mybatis Return primary key id

    Let's start with the uncommented Let's start with the entity class : public class City { private int city_id; private String city_name; public int getC ...

  3. Database sub database sub table ( One ) Common distributed primary keys ID Generation strategy

    Primary key generation policy The system is unique ID It is a problem that we often encounter when designing a system , Here are some common ID Generation strategy . Sequence ID UUID GUID COMB Snowflake The first self increase ID For the sake of reality ...

  4. mybatis Cannot get primary key after automatic generation id problem

    Use mybatis The primary key generated by the automatic generation tool of id: <selectKey resultType="java.lang.Integer" keyProperty="id ...

  5. Explain profound theories in simple language mybatis It returns the primary key ID

    Catalog Return the primary key when adding a single record ID Get the primary key value of the record in the mapper Get the primary key field value of the newly added record Return primary key when adding batch records ID Get primary key ID Realization principle Get the primary key after adding records ID, This is a very common requirement , Especially one time ago ...

  6. mybatis And mysql Returns the primary key when inserting id Value

    <insert id="insertCharge" parameterType=""> < ...

  7. Use mybatis Insert self incrementing primary key ID After the data is returned automatically ID

    In the development of user registration function need to use the user ID, But users ID It's generated by the database itself , In this case, use the following method to configure after online inquiry mybatis Of insert Statements can solve : <insert id="in ...

  8. Mybatis+Mysql Insert database and return auto incrementing primary key id Three ways to value

    One . scene : Insert the value of the database to get the returned primary key immediately id Carry on the next procedure operation Two . resolvent : The first one is : Use generic mapper The insertion method of Mapper.insertSelective(record): This method : ...

  9. mybatis The primary key is returned when the record is added id

    Reference resources :mybatis The primary key is returned when the record is added id scene Sometimes we want to get the primary key of the record directly after adding the record id value , You don't have to perform a query again . In the use of mybatis As ORM When the component , It's easy to reach this ...

  10. Mybatis Get the added auto increment primary key from ID( in the light of mysql)

    Share a blog , It's mainly for us to use SSM When , stay .xml In order to get <insert></insert> The self increasing primary key of Id, Because it's been a long time , At this time , A little strange , Just write a note here , ...

Random recommendation

  1. ROS Learning notes ( Two )——ubantu 14.04 install

    0. Dual system installation (U Disk installation ) 1. The installation file is in ubantu Download from the official website : ubantu Official website : ubuntu Of server Version and desktop What area does the edition have ? ( Come on ...

  2. Capitalize -(ASCII surface )

    #include<stdio.h> /* Turn capitalization ,ASCII surface . The difference between uppercase and lowercase 32 */ char upper(char c) { if(c>='a'&&c<= ...

  3. be based on go-ceph establish CEPH Block devices and snapshots

    One . Prepare for code execution 1. The system has CEPH colony 2.GOPATH Directory exists src/ The code base 3. stay ubuntu 14.04 We still need apt-get l ...

  4. PHP Basic use

    The basic use of this article includes : php Conventional grammar date,number,array And so on The general syntax of programming language is easy to understand , Almost the same . If you're a programmer good at other interpretive languages , Migrate to php It's almost effortless . ...

  5. webservice Publishing interface

    One : Write interface program , Computing function class , There are four ways to add, subtract, multiply and divide /** * */ package com.hlcui.util; /** * @author Administrator Publish this class as a public interface */ ...

  6. How to be in Ubuntu Create and manage LXC Containers ?

    take LXC The installation to Ubuntu On $ sudo apt-get install lxc After installation , function lxc-checkconifg Tools , Check current Linux The kernel support LXC The situation of . If everything is enabled , Inside ...

  7. WebService What is it

    WebService What is it Zhang Xiaoxiang WebService  http://wenku.baid ...

  8. How relational databases work - Statistical analysis of data characteristics ( Translated from Coding-Geek article )

    This article is translated from Coding-Geek article :< How does a relational database work>. Link to the original text : ...

  9. test markdown to html

    Software version PHP 5.5.25 Yaf 2.3.2 domain name Official domain name demo domain name To configure The configuration directory The background configuration con ...

  10. IDEA2018.2.2 Version configuration comment template

    Ctrl+Alt+S Enter the setting interface ( I haven't changed the keymapping , You can also File-OtherSetting Enter settings ), find Editor->File and Code Templates, First in Include ...