我有一个使用MyBatis访问PostgreSQL数据库的Java项目。PostgreSQL允许在INSERT语句之后返回新创建行的字段,我想使用它来返回新创建记录的自动生成的BIGSERIAL id。因此,我将XML中的insert命令更改为使用PostgreSQL的特性,将resultType="long"属性添加到<insert>标记,并在映射器的Java接口中将插入方法设置为返回long而不是void。
当我尝试运行这个程序时,我得到一个org.xml.sax.SAXParseException,上面写着Attribute "resultType" must be declared for element type "insert"。
现在,当我将<insert>标记更改为<select>时,一切正常,但是使用<select>标记执行INSERT语句让我感到困扰。
有没有一种方法可以让映射到<insert>标签的方法返回结果,或者MyBatis不是为此而设计的,我应该只将它们作为<select>标签?
发布于 2013-03-18 17:50:00
映射插入方法的返回类型可以是void或int (在这种情况下,它将返回插入的行号)。您可以通过以下机制返回生成的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集。
发布于 2013-03-20 03:35:29
您可以按如下方式使用。在xml中
<insert id="insertNewUser" parameterType="User">
<selectKey keyProperty="userId" resultType="Integer" order="BEFORE">
select NEXTVAL('base.user_id_seq')
</selectKey>
INSERT INTO base.user(
user_id, user_name)
VALUES (#{userId}, #{userName});
</insert>在调用要插入的方法的Java类中,可以通过调用user.getUserId()来获取值。
基本上,下一个val存储在对象的变量中。Here userId inside User.
发布于 2019-09-20 17:55:39
有两种方法(至少据我所知)可以获得所插入记录的ID:
例如,我们有一个类EntityDao
public class EntityDao {
private Long id;
private String name;
// other fields, getters and setters
}1.使用insert标签并返回object的实例
MyBatis接口
public interface EntityDaoMapper {
EntityDao insert(EntityDao entity);
}MyBatis XML映射器:
<insert id="insert" parameterType="com.package.EntityDao" useGeneratedKeys="true" keyColumn="entity_id" keyProperty="id">
INSERT INTO some_table (name, type, other_fields, etc)
VALUES (#{name}, #{type}, #{other_fields}, #{etc})
</insert>示例代码:
EntityDao saved = entityDaoMapper.insert(entityToSave);
System.out.println(saved.getId());2.使用select和resultType标签只返回记录的ID
MyBatis接口
public interface EntityDaoMapper {
Long insert(EntityDao entity);
}MyBatis XML映射器:
<select id="insert" parameterType="com.package.EntityDao" resultType="long">
INSERT INTO some_table (name, type, other_fields, etc)
VALUES (#{name}, #{type}, #{other_fields}, #{etc})
RETURNING entity_id <-- id only or many fields
</select>示例代码:
Long id = entityDaoMapper.insert(entityToSave);
System.out.println(id);https://stackoverflow.com/questions/15456033
复制相似问题