ibaties 注解式 insert后返回id

本文分享了在MyBatis中正确实现插入数据并获取生成ID的方法。通过使用@Insert注解定义SQL语句,在mapper接口中利用@Options注解设置useGeneratedKeys为true,keyProperty和keyColumn为'id',即可在service层调用插入方法后,直接通过对象的getId()方法获取到新插入记录的ID。

写这篇博客的是因为在网上找的不对,下面贴上正确的代码。

mapper里是这样的

  @Insert("insert into FilemanUrl(uid,fileInfoId,userName,orginname,opRight,logur1,uptime) " +
            "values (#{uId},#{fileInfoId},#{userName},#{orginName},#{opRight},#{logur1},#{upTime})")
  //下面这句代码就是将insert后的id拿到装配给bean
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    void addfilemanUrlByUpload(FilemanUrl filemanUrl);

 

service里是这样的

 fileUploadAndDownMapper.addfilemanUrlByUpload(filemanUrl);
//不用设返回值,mapper里新增的id就这样就可以拿到
  filemanRight.setFileUrlId(filemanUrl.getId());
                filemanRight.setFileInfoId(fileManFileInfo.getId());
                filemanRights.add(filemanRight);

 

在使用 MyBatis-Plus 进行插入操作时,如果希望将生成的主键 ID 注入到实体类中,可以通过以下方式实现。 MyBatis-Plus 默认使用了 MyBatis 的 `useGeneratedKeys` 和 `keyProperty` 特性来支持自增主键的回填。只要在实体类的主键字段上正确配置了 `@TableId` 注解,并且数据库表的主键设置为自增(如 MySQL 的 `AUTO_INCREMENT`),插入操作完成后,主键值会自动注入到实体对象中。 ### 示例代码 以下是一个使用 MyBatis-Plus 插入数据并获取生成的主键 ID 的示例: ```java import com.baomidou.mybatisplus.annotation.*; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; public class MyBatisPlusExample { @Data public static class User { @TableId(value = "id", type = IdType.AUTO) private Long id; private String name; private Integer age; } @Mapper public interface UserMapper extends BaseMapper<User> { } // 插入操作示例 public static void insertUser(UserMapper userMapper) { User user = new User(); user.setName("John Doe"); user.setAge(30); // 执行插入操作 userMapper.insert(user); // 插入完成后,主键值会被自动注入到 user 对象中 System.out.println("Generated ID: " + user.getId()); } } ``` ### 说明 1. **`@TableId` 注解**:用于标识主键字段,并指定数据库列名(`value` 属性)。`type = IdType.AUTO` 表示该主键由数据库自动生成(如自增)。 2. **`BaseMapper` 接口**:MyBatis-Plus 提供的 `BaseMapper` 包含常用的数据库操作方法,如 `insert`。 3. **插入操作**:调用 `userMapper.insert(user)` 插入数据后,生成的主键值会自动绑定到 `user` 对象的 `id` 字段中。 ### 注意事项 - 数据库表的主键必须设置为自增(例如 MySQL 的 `AUTO_INCREMENT`),否则无法自动回填主键值。 - 如果使用的是非自增主键(如 UUID 或自定义生成策略),需要手动设置主键值,而不是依赖数据库生成。 通过以上方法,可以确保在插入数据后,生成的主键 ID 被正确注入到实体类中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值