从 MyBatis <insert> 映射方法返回值

本文详细介绍了在MyBatis中通过insert标签与selectKey标签配合,如何实现插入操作后返回生成的ID,包括void和int返回类型,以及使用useGeneratedKeys和selectNextVal/currval获取自增ID的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

映射插入方法的返回类型可以是voidint(在这种情况下,它将返回插入行的编号)。您可以执行以下机制来返回生成的 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.使用selectandresultType标签只返回记录的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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值