mybatis插入返回自增主键

本文介绍在MyBatis中如何通过两种方式获取MySQL自增主键的值,包括单条插入和批量插入的方法,并提供具体的XML配置与Java代码示例。

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

昨天下班到家以后收到一朋友问我一个问题:mysql中设置的是自增主键,然后在Mybatis执行insert语句后如何返回自增主键值,我说明天我到公司后写一篇博客给你

Mybatis官网是这样说的:

First, if your database supports auto-generated key fields (e.g. MySQL and SQL Server), then you can simply set useGeneratedKeys="true" and set the keyProperty to the target property and you're done. For example, if the Authortable above had used an auto-generated column type for the id, the statement would be modified as follows:

就是说需要useGenerateKeys=“true”和keyProperty=“XXId”,但是需要下面这些前置条件

1、升级Mybatis版本到3.3.1。

2、在Dao中不能使用@param注解。

一、单条insert返回自增主键,方案一

好了废话不多说,直接上代码

user.xml

<insert id="insert" parameterType="com.test.User">
    INSERT INTO User
     <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="id != null" >taskScheduleId,</if>
        <if test="userName != null" >clearSettleFileId,</if>
        <if test="age!= null" >inputDate,</if>
        <if test="address != null" >fileDate,</if>
    </trim>
    <trim prefix="VALUES (" suffix=")" suffixOverrides="," >
        <if test="id != null" >#{id,jdbcType=INTEGER},</if>
        <if test="userName != null" >#{userName,jdbcType=VARCHAR},</if>
        <if test="age != null" >#{age,jdbcType=VARCHAR},</if>
        <if test="address != null" >#{address,jdbcType=VARCHAR},</if>       
    </trim>
    <selectKey resultType="java.lang.Integer" keyProperty="id">
        SELECT LAST_INSERT_ID() AS id    
    </selectKey>
</insert>

UserServiceImpl.java

User vo = new User();
vo.setUserName("zhangsan");
vo.setAge("20");
vo.setAddress("a");
dao.insert("insert",vo);

System.out.println(vo.getId());

二、单条insert返回自增主键,方案二

就是xml但变动,java类不需要变动

<insert id="insert" parameterType="com.test.User" keyProperty="taskScheduleId" useGeneratedKeys="true">
    INSERT INTO User
     <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="id != null" >taskScheduleId,</if>
        <if test="userName != null" >clearSettleFileId,</if>
        <if test="age!= null" >inputDate,</if>
        <if test="address != null" >fileDate,</if>
    </trim>
    <trim prefix="VALUES (" suffix=")" suffixOverrides="," >
        <if test="id != null" >#{id,jdbcType=INTEGER},</if>
        <if test="userName != null" >#{userName,jdbcType=VARCHAR},</if>
        <if test="age != null" >#{age,jdbcType=VARCHAR},</if>
        <if test="address != null" >#{address,jdbcType=VARCHAR},</if>       
    </trim>
</insert>

二、批量插入insert返回自增主键

user.xml

<insert id="insertBatch" parameterType="list" keyProperty="id" useGeneratedKeys="true">
    INSERT INTO User(
        userName,
        age,
        address)VALUES
        <foreach collection="list" item="item" separator="," index="index">
            <trim prefix="(" suffix=")" suffixOverrides=",">
            #{item.userName,jdbcType=VARCHAR},
            #{item.age,jdbcType=VARCHAR},
            #{item.address,jdbcType=VARCHAR}
            </trim>
        </foreach>
</insert>

### 实现 MyBatis 插入操作后返回主键 ID 为了使 MyBatis 在执行插入语句之后能够获取并返回数据库生成的自主键,可以在 `<insert>` 标签内设置 `useGeneratedKeys` 属性为 true 并指定 `keyProperty` 来映射实体类字段与数据库列之间的关系。 #### XML 配置示例 ```xml <insert id="insertLawsB" parameterType="com.test.entity.main.LawsB" useGeneratedKeys="true" keyProperty="id"> <!-- 警告 - @mbggenerated 此元素由 MyBatis Generator 自动生成,请勿修改 --> insert into LAWS_B ( TYPE, NAME, PDATE ) values ( #{type,jdbcType=NVARCHAR}, #{name,jdbcType=NVARCHAR}, #{pdate,jdbcType=NVARCHAR} ) </insert> ``` 这段配置说明了如何定义一个名为 `insertLawsB` 的 SQL 映射语句[^1]。其中: - **parameterType**: 定义传入参数的数据类型; - **useGeneratedKeys=true**: 表明此条目将利用 JDBC 获取自动产生的键值; - **keyProperty=id**: 将新生成的主键赋给 Java 对象对应的属性名; 对于 MySQL 数据库而言,在同一个连接上下文中可以通过调用 `LAST_INSERT_ID()` 函数来取得最近一次成功执行 INSERT 命令所创建的第一行记录的第一个 AUTO_INCREMENT 列的值[^2]。 需要注意的是,当使用 MyBatis 执行插入操作时,默认情况下返回的结果是受影响的行数而非具体的主键值。如果希望得到刚插入记录的主键,则需按照上述方式进行适当调整以确保主键能被正确填充回原始对象实例中去[^3]。 此外,还有一种情况是在某些场景下可能会遇到即使设置了正确的配置也无法正常工作的情况,这可能是由于缓存或其他因素引起的异常行为。此时建议开启调试模式查看具体流程以便更好地定位问题所在[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值