如何使用 MyBatis 获取插入的生成 key ? 我读了很多关于这个问题的页面,但我仍然被阻止,有人可以帮助我吗? 这是我的代码:
table :
ID_ERROR long primary key
DATE timestamp
TYPE varchar
MESSAGE varchar
SOURCE varchar
道:
Long returnedId = 0L;
MyMapper myMapper = this.sqlSession.getMapper(MyMapper.class);
myMapper.insertRecord(returnedId, Utils.now(), t.getClass().getName(), t.getMessage(), c.getName());
return returnedId;
mapper.java:
public void insertRecord(@Param("returnedId") Long returnedId, @Param("timestamp")Timestamp timestamp,@Param("type") String type,@Param("message") String message,@Param("source") String source);
mapper.xml
<insert id="insertRecord" parameterType="map" useGeneratedKeys="true" keyProperty="ID_ERROR">
INSERT INTO errors (
DATE,
TYPE,
MESSAGE,
SOURCE
)
VALUES (
#{timestamp},
#{type},
#{message},
#{source}
)
<selectKey resultType="long" order="AFTER" keyProperty="returnedId">
SELECT LAST_INSERT_ID() as returnedId
</selectKey>
</insert>
怎么了?如何获取此插入的生成 key ? 谢谢!
最佳答案
对我来说它是这样工作的(mybatis 3.x).. mysql表中id必须设置自增
<insert id="createEmpty" parameterType="Project" useGeneratedKeys="true" keyProperty="project.projectId" keyColumn="PROJECT_ID">
INSERT INTO PROJECT (TITLE,DESCRIPTION)
VALUES
(#{title},#{description})
</insert>
NOTE keyProperty="project.projectId"
和 useGeneratedKeys="true"
我的界面是:
public int createEmpty(@Param("project") Project project, @Param("title") String title,
@Param("description") String description);
最后得到我使用的值(将自动分配给 pojo 的 id 属性):
projectRepository.createEmpty(p, "one", "two");
System.err.print(p.getProjectId() + "\n");
关于java - MyBatis,如何获取插入的自动生成 key ? [MySql],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18507508/