Ida*_*rye 15 postgresql mybatis
我有一个使用MyBatis访问PostgreSQL数据库的Java项目.PostgreSQL允许在INSERT语句后返回新创建的行的字段,我想用它来返回自动生成BIGSERIAL id的新创建的记录.因此,我insert将XML中的命令更改为使用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>标签保存?
par*_*lov 20
映射插入方法的返回类型可以是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})
</isnert>
Run Code Online (Sandbox Code Playgroud)
这会将生成的id列设置id为参数类的属性.之后,作为参数传递的对象将id在其属性中生成set.
小智 6
您可以按如下方式使用。在 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>
Run Code Online (Sandbox Code Playgroud)
在调用插入方法的 Java 类中,您可以通过调用获取值 user.getUserId().
基本上下一个 val 存储在对象的变量中。 Here userId inside User.
有两种方法(至少我知道)可以获取一条插入记录的 ID:
例如,我们有一个类EntityDao:
public class EntityDao {
private Long id;
private String name;
// other fields, getters and setters
}
Run Code Online (Sandbox Code Playgroud)
insert标签并返回对象的实例MyBatis 界面
public interface EntityDaoMapper {
EntityDao insert(EntityDao entity);
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
示例代码:
EntityDao saved = entityDaoMapper.insert(entityToSave);
System.out.println(saved.getId());
Run Code Online (Sandbox Code Playgroud)
select和resultType标签只返回记录的IDMyBatis 界面
public interface EntityDaoMapper {
Long insert(EntityDao entity);
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
示例代码:
Long id = entityDaoMapper.insert(entityToSave);
System.out.println(id);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37392 次 |
| 最近记录: |