从MyBatis< insert>返回值映射方法 [英] Returning values from MyBatis <insert> mapped methods

查看:666
本文介绍了从MyBatis< insert>返回值映射方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java项目,该项目使用MyBatis访问PostgreSQL数据库. PostgreSQL允许在INSERT语句之后返回新创建的行的字段,我想用它来返回新创建的记录的自动生成的BIGSERIAL id.因此,我更改了XML中的insert命令以使用PostgreSQL的功能,向<insert>标签添加了resultType="long"属性,并且在映射器的Java接口中,我将插入方法设置为返回long void.

I have a Java project that uses MyBatis to access a PostgreSQL database. PostgreSQL allows to return fields of a newly created row after an INSERT statement, and I want to use it to return the auto-generated BIGSERIAL id of newly created records. So, I change the insert command in the XML to use feature of PostgreSQL, add an resultType="long" attribute to the <insert> tag, and in the Java interface of the mapper I set the insertion method to return long instead of void.

当我尝试运行此命令时,我得到一个org.xml.sax.SAXParseExceptionAttribute "resultType" must be declared for element type "insert".

When I try to run this, I get an org.xml.sax.SAXParseException saying that Attribute "resultType" must be declared for element type "insert".

现在,当我将<insert>标记更改为<select>时,一切正常,但是让我感到困扰的是,我使用<select>标记执行INSERT语句.

Now, when I change the <insert> tag to <select> everything works fine, but it bothers me that I use <select> tag to perform an INSERT statement.

是否有一种方法可以使映射到<insert>标记的方法返回结果,或者MyBatis不是为此而设计的,我应该将它们保留为<select>标记?

Is there a way to make methods mapped to <insert> tags return results, or is MyBatis not designed for that, and I should just keep them as <select> tags?

推荐答案

映射插入方法的返回类型可以是voidint(在这种情况下,它将返回插入行的编号).您可以执行以下机制来返回生成的ID:

The return type of mapped insert method can be void or int (in which case it will return the number of the inserted row). You can do the following mechanism to return the generated id:

<insert id="insert" parameterClass="MyParameter">
  <selectKey order="AFTER" keyProperty="id" resultType="long">
    SELECT currval('my_seq')
  </selectKey>
  INSERT INTO mytable(col1, col2) VALUES (#{val1}, #{val2})
</insert>

这会将生成的id列设置为参数类的id属性.之后,您作为参数传递的对象将在其属性中生成id设置.

This will set generated id column to id property of your parameter class. After that, object you passed as parameter will have generated id set in its property.

这篇关于从MyBatis&lt; insert&gt;返回值映射方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆