Mybatis中添加一条数据的同时返回自增主键ID
"在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即为返回的自增主键.
相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
sushuanglei 2020-11-12
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gaobudong 2020-11-04
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30