映射插入方法的返回类型可以是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
在其属性中生成集合。
您可以如下使用。在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.
有两种方法(至少我知道)来获取一个插入记录的 ID:
例如,我们有一个类EntityDao
:
public class EntityDao {
private Long id;
private String name;
// other fields, getters and setters
}
1. 使用insert
标签并返回一个对象实例
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
andresultType
标签只返回记录的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);