Open GenweiWu opened 2 years ago
useGeneratedKeys设置为true,然后把keyColumn指定的数据库表字段,保存到parameterType对应类的keyProperty字段
<insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
即插入开始前id是null,插入完成后id就被填充值了
@Test
public void testInsert() {
User user = new User();
user.setName("tianshouzhi");
user.setAge(27);
System.out.println("插入前 id:" + user.getId());
sqlSession.insert("com.tianshouzhi.mybatis.batch.mappers.UserMapper.insert", user);
System.out.println("插入后:" + user.getId());
}
<insert id="insert" useGeneratedKeys="true" keyProperty="id" keyColumn="user.id">
INSERT INTO user (name, age) VALUES (#{user.name}, #{user.age})
</insert>
insert(@Param("user") userInfo)
https://stackoverflow.com/a/42162859 则循环对象要取名为list
<insert id="batchInsert" parameterType="list" useGeneratedKeys="true" keyProperty="id"> <!-- obj2 is the object with variable id to store generated key --> insert into object2 (value) values <foreach collection="list" item="obj1" separator=","> (#{obj1.xxx}) </foreach>
RETURNING
关键字常见用法:insert后returning
结合mybatis的用法
参考