在mapper.xml中指定keyProperty和useGeneratedKeys属性,其中id为返回的主键对应的java对象的属性
useGeneratedKeys="true" keyProperty="id"
mapper.xml内容:
<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.yhr.pojo.User">
insert into user(userName,password,comment)
values(#{userName}
</insert>
javaBean内容:
public class User {
private int id; //与keyProperty对应
private String userName;
private String password;
private String comment;
//setter and getter.....
}
调用方式:
userDao.insert(user);//插入操作
System.out.println("插入后主键为:"+user.getId()); //插入后会把主键id自动赋给user对象