您的位置:首页 > 数据库 > MySQL

MyBatis+MySQL 返回插入的主键ID

2016-08-10 15:22 459 查看
需求:使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值。

 

方法:在mapper中指定keyProperty属性,示例如下:

<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">
insert into user(userName,password,comment)
values(#{userName},#{password},#{comment})
</insert>
 如上所示,我们在insert中指定了keyProperty="userId",其中userId代表插入的User对象的主键属性。

 

useGeneratedKeys 取值范围true|false 默认值是:false。 含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。

User.java

<span><span class="keyword">public</span><span> </span><span class="keyword">class</span><span> User {
</span></span>
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);

}

测试:
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());

 输出:
插入前主键为:0
插入后主键为:15
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: