Home > Java > javaTutorial > body text

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

Y2J
Release: 2017-05-06 13:29:56
Original
3516 people have browsed it

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>
Copy after login

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 
}
Copy after login

UserDao.java

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

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());
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!