需求:使用
MyBatis
往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值。-
Mybatis xml文件:
<insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user (username,age,comment) VALUES(#{userName},#{age},#{comment})
</insert> -
User PO类:
public class User {
private Long id;
private String userName;
private Integer age;
private String comment;
/**
* getters && setters
*/
} -
Dao类:
public interface UserDao {
public int insert(User user);
} -
测试类:
User user = new User();
user.setUserName("jiazhipeng");
user.setAge(24);
user.setComment("测试插入数据返回主键功能");
System.out.println("插入前主键为:"+user.getId());
userDao.insert(user);
System.out.println("插入后主键为:"+user.getId()); -
输出:
插入前主键为:0
插入后主键为:111