Mybatis obtains the value of self incrementing primary key (Mysql and Oracle)

Posted by greyhoundcode on Wed, 05 Jan 2022 14:00:28 +0100

pojo:

public class User {
    private Integer id;
    private String name;
    private String pwd;
    setter and getter....
}

Database:

1. Gets the value of the self incrementing primary key

Mapping file:

	<!-- UserMapper Interface public void addUser(User user); -->
	<insert id="addUser" parameterType="com.workhah.pojo.User" useGeneratedKeys="true" keyProperty="id" databaseId="mysql">
		insert into user(name,pwd) 
		values(#{name},#{pwd})
	</insert>

Get the value of self incrementing primary key:

  • M y s q l Mysql Mysql supports self incrementing primary keys and obtaining self incrementing primary key values, M y b a t i s Mybatis Mybatis also uses statement getGenreatedKeys()
  • useGeneratedKeys="true" use self incrementing primary key to obtain primary key value policy
  • keyProperty specifies the corresponding primary key property, that is M y b a t i s Mybatis After Mybatis obtains the primary key value, it encapsulates the value to j a v a B e a n javaBean Which property of a javaBean.

Test to get the primary key value:

    @Test
    public void test() {
        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User(0, "workhah", "123");
        mapper.addUser(user); 
        System.out.println(user.getId());	// 14
        // Originally, there were 13 pieces of data in the user table. Now insert a piece of data, and the id of the data is 14, and the value of the self increasing primary key id is returned to the user variable.
    }

Originally, there were 13 pieces of data in the user table. Now insert a piece of data, and the id of the data is 14, and the value of the self increasing primary key id is returned to the user variable.

Therefore, it should be noted that if you want to obtain the value of self incrementing primary key, you must have a corresponding value J a v a B e a n JavaBean JavaBean class (such as the user variable in the above example), which encapsulates the value of self incrementing primary key.

2. Gets the value of a non self incrementing primary key

Oracle does not support auto increment; Oracle uses sequence to simulate auto increment; The primary key of each inserted data is the value obtained from the sequence;

	<!-- UserMapper Interface public void addUser(User user); -->
	<insert id="addUser" databaseId="oracle">
		<selectKey keyProperty="id" order="BEFORE" resultType="Integer">
			<!-- Write query primary key sql sentence -->
			<!-- BEFORE-->
			select USER_SEQ.nextval from dual 
		</selectKey>
		
		<!-- The primary key at the time of insertion is obtained from the sequence -->
		<!-- BEFORE:-->
		insert into user(id,name,pwd) 
		values(#{id},#{name},#{pwd})
	</insert>
  • keyProperty: the found primary key value is encapsulated to j a v a B e a n javaBean Which property of javaBean

  • order="BEFORE": the current sql is run before the sql is inserted
    AFTER: the current sql is run AFTER the sql is inserted

    • BEFORE running sequence:
      Run the sql of selectKey query id first; Find out the id value encapsulated to j a v a B e a n javaBean id attribute of javaBean
      Insert sql at run time; You can retrieve the value corresponding to the id attribute
    • AFTER running sequence:
      Run the inserted sql first (take the new value from the sequence as the id)
      Then run the sql of selectKey query id;
  • resultType: the return value type of the found data

Test to get the primary key value:

    @Test
    public void test() {
        SqlSession sqlSession = MyTest.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User(0, "workhah", "123");
        mapper.addUser(user); 
        System.out.println(user.getId());	// 12
    }

reflection

problem

Since the selectKey is executed in advance, the obtained primary key value is encapsulated in the J a v a B e a n JavaBean In the JavaBean, and then execute the sql statement as the input of sql, can the selectKey obtain other values, or even the data obtained from another table as the output

verification

The answer is yes!
blog class

public class Blog {
    private int id;
    private String title;
    private String author;
    private String createTime;
    private int views;
    setter and getter....
}

Mapping file

<!-- UserMapper Interface public void updateUser(Blog blog); -->
<update id="updateUser" parameterType="user">
	<selectKey keyProperty="title" resultType="String" order="BEFORE">
		select title from blog where id = 1
	</selectKey>
	update user set name = #{title} where id = 13
</update>

test

@Test
    public void test() {
        SqlSession sqlSession = MyTest.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Blog blog = new Blog(0, null, null, null,0);
        System.out.println(blog);
        // result
        // Blog(id=0, title=Mybatis, author=null, createTime=null, views=0)
    }

database

The return value of the selectKey is used as the input of the sql statement, and the database is successfully modified and returned to the variable blog. Although this interface method can realize cross table, it needs blog class parameter cooperation. In actual development, the logic is strange. Here is only used to verify the problem guess.

Topics: MySQL Oracle Mybatis