写代码的时候使用到了SELECT LAST_INSERT_ID(),发现每次返回的结果都是1,用PO取主键则每次都是0
public class ManagerPO {
private int id;
private String account;
private String password;
private String phone;
private String name;
private boolean deleted;
private DateTime createTime;
private DateTime updateTime;
}
ManagerPO 的mybatis配置如下:
<insert id="create" useGeneratedKeys="true" keyProperty="ID">
<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="ID">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO SIN_Manager (Account,Password,Name,Phone,Deleted)
VALUES (#{account}, #{password},#{name},#{phone},0)
</insert>
JAVA调用如下:
ManagerPO managerPO = new ManagerPO();
managerPO.setAccount(account);
managerPO.setPassword(password);
managerPO.setName(name);
managerPO.setPhone(phone);
int result= managerDAO.create(managerPO);
System.out.println("result="+result);
System.out.println("managerPOId="+managerPO.getId());
执行结果为:
result=1
managerPOId=0
注意点一:执行insert()方法,期望是每次返回上一次插入的数据的主键id,然而每次都返回1,经过一番检查后,发现"select last_insert_id()"已经执行了但是并不是这个方法的返回值,
而"select last_insert_id()"语句的结果被封装到了student对象中了,所以执行完sql语句后可以通过managerPO.getId();获得新插入记录的主键。
对比我们的输出结果返现有两个问题,第一个是取返回插入主键取错了。不应该取result,应该取managerPO.getId()。
那为什么这里managerPOId=0,答案在mybatis配置文件里忽略了keyProperty大小写问题。修改一下:
<insert id="create" useGeneratedKeys="true" keyProperty="id">
<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO SIN_Manager (Account,Password,Name,Phone,Deleted)
VALUES (#{account}, #{password},#{name},#{phone},0)
</insert>
执行结果如下,问题解决!
result=1
managerPOId=32