`

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即为返回的自增主键.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics