(6) MyBatis from entry to soil-the acquisition of the primary key

This is the sixth in the mybatis series. If you haven't read the previous suggestions, first go to the [Java Tsukuba Fox] public account to view the previous text, which is convenient for understanding and grasping.

The first five articles have basically introduced the basic usage of MyBatis. It is strongly recommended that you read the first five articles and then read the next content after reading the actual operation.

Add, delete and modify the return value description

Add, delete, or modify the db in mybatis, whether it is adding, deleting, or modifying, its essence is to use the corresponding method in jdbc, that is, the executeUpdate method of java.sql.Statement, or the executeUpdate method of java.sql.PreparedStatement .

So the key to the problem is to master the content of these two methods, and the parameters of these two methods are inconsistent but the return value is int, which is used to indicate the number of rows affected.

The return value of Mybatis supports int, and also supports Integer, long, Long, boolean, Boolean, and void, which greatly enhances the flexibility and diversity of programming.

But smart friends must know that MyBatis can support so many types, in fact, mybatis converts the int type to other types internally. Nothing advanced,

After understanding the return value of the addition, deletion, and modification check, we will look at how jdbc and mybatis obtain the primary key in the next step.

Several ways to get the primary key of jdbc

Before talking about the way jdbc obtains the primary key, let's think about how the primary key of the database is generated.

That mysql example: in mysql, when we insert data into the table, if the primary key (id) is not specified, then mysql will automatically generate the id, but in some business we will need this id later, we need to think Ways to get this id, especially this kind of auto-generated self-increment id.

To have a clear understanding, you need to look at how jdbc is implemented

Method 1: jdbc built-in method

usage

The jdbc developers have already thought of the need to obtain the primary key, and have also developed the corresponding api to help us program, see the getGeneratedKeys method in the java.sql.Statement class for details

From this method, we know that this method will return a result set from which the value of the self-incrementing primary key can be obtained. But there is a prerequisite for using this method, that is, a setting needs to be made when executing sql.

If you execute sql through java.sql.Statement, you need to call the following method:

int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException

Note that the second parameter of the above method needs to be set to java.sql.Statement.RETURN_GENERATED_KEYS, indicating that the value of the auto-increment column needs to be returned.

However, in most cases, we will use the java.sql.PreparedStatement object to execute sql. If you want to obtain self-value added, you need to set the value of the second parameter to create this object, as follows:

PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

Then we can get the auto-growth value through the ResultSet object returned by getGeneratedKeys, as follows:

ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys!=null && generatedKeys.next()) {
    log.info("自增值为:{}", generatedKeys.getInt(1));
}

Method 2: Query to obtain after inserting

usage

Of course, in addition to jdbc thought of our needs, mysql database also thought of this demand, and there are corresponding statements to help us get the id value of the latest inserted record after inserting data, as shown below

SELECT LAST_INSERT_ID()

So we can immediately use the current connection to send the above SQL to get the value of the auto-increment column after inserting it. This method is relatively simple and convenient, but there are some problems, that is, serious problems may occur in the case of high concurrency and multithreading, so it is generally not recommended to use it.

Method 3: Obtain before inserting

The last method is to get it before inserting.

I don’t know if you have played oracle, there is no automatic growth column in mysql, but Oracle has a function that can realize automatic growth. This function is a sequence. The sequence is equivalent to an auto-increment device with an initial value. Incremental step size. Of course, this sequence provides some functions for us to use. You can get the current value and next value of the sequence. The usage is as follows:

  • First define a sequence
  • Get the next value: SELECT sequence name. NEXTVAL FROM dual;

3 ways for mybatis to get the primary key

Since jdbc has three methods, mybatis also has several corresponding methods.

Method 1: Use the built-in jdbc method internally

usage

Mybatis uses the built-in jdbc method mentioned above.

We need to configure in Mapper xml, such as:

<insert id="insertUser1" parameterType="zhonghu.mybatis.chat01.UserModel" useGeneratedKeys="true" keyProperty="id">
    <![CDATA[
    INSERT INTO user (name,age,salary) VALUES (#{name},#{age},#{salary})
     ]]>
</insert>

There are 2 key parameters that must be set:

  • useGeneratedKeys: set to true
  • keyProperty: The name of the property in the parameter object. After the final insertion is successful, mybatis will set the self-value added to the property specified by keyProperty through reflection.

Method 2: Query to obtain the primary key after inserting

usage

This method is the same as the second method of jdbc described above. After inserting, the value of the primary key is obtained through query and then filled in the specified attribute. The mapper xml configuration is as follows:

<insert id="insertUser2" parameterType="zhonghu.mybatis.chat01.UserModel">
    <selectKey keyProperty="id" order="AFTER" resultType="long">
    <![CDATA[
    SELECT LAST_INSERT_ID()
     ]]>
    </selectKey>
    <![CDATA[
    INSERT INTO user (name,age,salary) VALUES (#{name},#{age},#{salary})
     ]]>
</insert>

The key code is the part contained in the selectKey element. This element can contain a sql. This sql can be run before or after the insert (before or after the order attribute is configured), and then the result of the sql operation will be set to the attribute specified by the keyProperty , SelectKey element has 3 attributes that need to be specified:

  • keyProperty: The name of the property in the parameter object. After the final insertion is successful, mybatis will set the self-value added to the property specified by keyProperty through reflection.
  • order: Specify whether the sql in the selectKey element is run before or after the insertion, optional value (BEFORE|AFTER), in this way we choose AFTER
  • resultType: the type corresponding to the attribute specified by keyProperty, for example, the type corresponding to the id above is java.lang.Long, we directly write the alias long

Method 3: Query to obtain the primary key before inserting

usage

This method is the same as the third method of jdbc described above. Before inserting, the value of the primary key is obtained through a query and then filled in the specified attribute, and then the insert is executed. The mapper xml configuration is as follows:

<insert id="insertUser3" parameterType="zhonghu.mybatis.chat01.UserModel">
    <selectKey keyProperty="id" order="BEFORE" resultType="long">
    <![CDATA[ 获取主键的select语句 ]]>
    </selectKey>
    <![CDATA[
    INSERT INTO user (name,age,salary) VALUES (#{name},#{age},#{salary})
     ]]>
</insert>

The key code is the part contained in the selectKey element. This element can contain a sql. This sql can be run before or after the insert (before or after the order attribute is configured), and then the result of the sql operation will be set to the attribute specified by the keyProperty , SelectKey element has 3 attributes that need to be specified:

  • keyProperty: The name of the property in the parameter object. After the final insertion is successful, mybatis will set the self-value added to the property specified by keyProperty through reflection.
  • order: Specify whether the sql in the selectKey element is run before or after the insertion, optional value (BEFORE|AFTER), in this way we choose BEFORE
  • resultType: the type corresponding to the attribute specified by keyProperty, for example, the type corresponding to the id above is java.lang.Long, we directly write the alias long

to sum up

This article focuses on some advanced usage methods of adding, deleting, modifying and checking in mybatis, especially the method of obtaining the primary key. Here, a comparison of jdbc and mybatis introduces three methods.

At last

  • If you feel that you are rewarded after reading it, I hope to pay attention to it. By the way, give me a thumbs up. This will be the biggest motivation for my update. Thank you for your support.
  • Welcome everyone to pay attention to my public account [Java Fox], focusing on the basic knowledge of java and computer, I promise to let you get something after reading it, if you don’t believe me, hit me
  • Seek one-click triple connection: like, forward, and watching.
  • If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love.

——I am Chuhu, and I love programming as much as you.

Welcome to follow the public account "Java Fox" for the latest news

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/113819713