How can I return the id of the inserted data when mybatis performs the insert operation ?, Mybatisinsert
1. useGeneratedKeys = "true" to obtain the auto-growth ID. Only the databases with auto-growth mode are supported (mysql, mssql, etc., but oracle does not support this). Therefore, selectKey can be used to obtain the ID.
Eg:
<insert id="xxx" parameterType="yyy" useGeneratedKeys="true">
insert into table(...) values (...)
<selectKey resultType="long" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID() AS id
</selectKey>
</insert
2. For Primary keys (such as Oracle) that cannot be automatically generated, you can use the following methods:
<insert id="xxx" parameterType="yyy">
<selectKey keyProperty="id" resultType="long" order="BEFORE">
select my_seq.nextval from dual
</selectKey> ... </insert>
For the first better solution:
Method: Specify the keyProperty in mapper, for example:
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">
insert into user(userName,password,comment)
values(#{userName},#{password},#{comment})
</insert>
As shown above, keyProperty = "userId" is specified in insert, where userId represents the primary key attribute of the inserted User object.
User.java
Java code Favorite code
public class User {
private int userId;
private String userName;
private String password;
private String comment;
// setter and getter
}
UserDao.java
Java code Favorite code
public interface UserDao {
public int insertAndGetId (User user);
}
test:
Java code Favorite code
User user = new User ();
user.setUserName ("chenzhou");
user.setPassword ("xxxx");
user.setComment ("Test insert function to return primary key function");
System.out.println ("The primary key before inserting is:" + user.getUserId ());
userDao.insertAndGetId (user); // Insert operation
System.out.println ("The primary key after inserting is:" + user.getUserId ());
Output:
Shell code Favorite code
The primary key before insertion is: 0
After inserting the primary key: 15
As shown above, the primary key id of the record just inserted is 15
Reprinted from: http://blog.csdn.net/rapier512/article/details/51198684
View comments