Mybatis中添加一条数据的同时返回自增主键ID

本文介绍如何在Mybatis中配置插入数据时自动获取并返回自增主键ID的方法。通过设置<insert>标签的useGeneratedKeys及keyProperty属性实现。适用于支持主键自增的数据库如MySQL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

"在Mybatis中,添加一条数据的同时返回其自增主键ID值"

方法:在mapper.xml文件中进行配置keyProperty属性.
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.oolin.User">
insert into user(userName,password)
values(#{userName},#{password})
</insert>


ps:userGeneratedKeys="true"(其配置要求是数据库本身具备主键自增功能,如Mysql,SqlServer就可以配置useGeneratedKeys=true.不支持主键自增的数据库其useGeneratedKeys的值不能为true.

实例:
insert中指定了keyProperty="userId",其中userId是插入的User对象的Id属性.
1.POJO
public class User {
private int userId;
private String userName;
private String password;

//setter and getter
}

2.UserDao
public interface UserDao {

public int addUser(User user);

}

3.测试
User user = new User();
user.set....
userDao.addUser(user);
Integer id = user.getId();

4.其中的Id即为返回的自增主键.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值