Home  >  Article  >  Java  >  Java implementation of instance method that returns newly added primary key ID

Java implementation of instance method that returns newly added primary key ID

Y2J
Y2JOriginal
2017-05-06 13:29:563514browse

This article mainly introduces the method of MyBatis+MySQL to return the inserted primary key ID. It has certain reference value. Interested friends can refer to it.

Requirement: After using MyBatis to insert a record into the MySQL database, the auto-incremented primary key value of the record needs to be returned.

Method: Specify the keyProperty attribute in mapper. The example is as follows:

<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, we specified keyProperty="userId" in insert, where userId represents the inserted User The primary key attribute of object .

User.java

public class User { 
  private int userId; 
  private String userName; 
  private String password; 
  private String comment; 

  //setter and getter 
}

UserDao.java

public interface UserDao {  
  public int insertAndGetId(User user);  
}

Test:

User user = new User(); 
user.setUserName("chenzhou"); 
user.setPassword("xxxx"); 
user.setComment("测试插入数据返回主键功能"); 

System.out.println("插入前主键为:"+user.getUserId()); 
userDao.insertAndGetId(user);//插入操作 
System.out.println("插入后主键为:"+user.getUserId());

Output:

The primary key before insertion is: 0
The primary key after insertion is: 15

[Related recommendations]

1. Java Free Video Tutorial

2. JAVA Beginner's Video Tutorial

3. JAVA Tutorial Manual

The above is the detailed content of Java implementation of instance method that returns newly added primary key ID. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn