存储压缩:不是“挤水分”,而是让数据“轻装上阵
2025/12/26 19:10:58
在 MyBatis 中插入数据后返回自增 ID 有以下几种常用方法:
useGeneratedKeys和keyProperty(推荐)<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> INSERT INTO user(name, age) VALUES(#{name}, #{age}) </insert>@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})") @Options(useGeneratedKeys = true, keyProperty = "id") int insertUser(User user);<selectKey>元素(支持更多数据库)<insert id="insertUser" parameterType="User"> <selectKey keyProperty="id" resultType="int" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO user(name, age) VALUES(#{name}, #{age}) </insert><insert id="insertUser" parameterType="User"> <selectKey keyProperty="id" resultType="int" order="BEFORE"> SELECT SEQ_USER.NEXTVAL FROM DUAL </selectKey> INSERT INTO user(id, name, age) VALUES(#{id}, #{name}, #{age}) </insert><insert id="insertUser" parameterType="User"> <selectKey keyProperty="id" resultType="int" order="AFTER"> SELECT currval('user_id_seq') </selectKey> INSERT INTO user(name, age) VALUES(#{name}, #{age}) </insert>// 实体类 public class User { private Integer id; // 主键属性 private String name; private Integer age; // getter/setter... } // 使用示例 User user = new User(); user.setName("张三"); user.setAge(25); // 执行插入 int result = userMapper.insertUser(user); // 插入后,id 会自动设置到 user 对象中 System.out.println("生成的ID:" + user.getId()); // 直接获取<insert id="batchInsert" useGeneratedKeys="true" keyProperty="id"> INSERT INTO user(name, age) VALUES <foreach collection="list" item="item" separator=","> (#{item.name}, #{item.age}) </foreach> </insert>List<User> userList = new ArrayList<>(); // 添加多个 user userMapper.batchInsert(userList); // 每个 user 对象的 id 都会被自动设置数据库支持:需要数据库支持自增主键
keyProperty 配置:必须与实体类的主键属性名一致
事务管理:在事务中,ID 会在事务提交后才真正确定
连接池:使用连接池时,确保useGeneratedKeys能正常工作
<insert id="batchInsertUsers" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id"> INSERT INTO user(name, age) VALUES <foreach collection="list" item="user" separator=","> (#{user.name}, #{user.age}) </foreach> </insert>// 在插入前生成 ID String uuid = UUID.randomUUID().toString(); user.setId(uuid); userMapper.insert(user); // 或者通过 selectKey 生成MySQL/PostgreSQL:使用useGeneratedKeys
Oracle:使用<selectKey>的BEFORE模式
批量插入:确保连接池配置支持返回多个 ID
这样插入后,ID 会自动填充到传入的实体对象中,无需额外查询。