在工作中遇到mybatis连接postgresl批量插入要获取主键对应的序列值问题,今天特此整理一下作为记录。
本文主要涉及的版本:mybatis:3.4.1;mybatis-spring:1.3.0
下面用的test实体定义:
private Integer id;
private String name;
private Integer age;
数据库的id为主键,id的默认值为一个序列:
CREATE TABLE "public"."test" (
"id" int4 NOT NULL DEFAULT nextval('test_seq'::regclass),
"name" varchar(255) COLLATE "pg_catalog"."default",
"age" int2
)
单个数据插入:
方法一:
mapper接口中的写法
void insetTest(Test test);
xml中的写法:
<insert id="insetTest" useGeneratedKeys="true" keyProperty="id">
insert into test ( name, age) values ( #{name} , #{age})
</insert>
方法二:
mapper接口中使用param注解参数
void insetTest(@Param("test")Test test);
xml中的写法,注意keyProperty是"test.id"。
<insert id="insetTest" useGeneratedKeys="true" keyProperty="test.id">
insert into test ( name, age) values ( #{name} , #{age})
</insert>
批量数据插入
mapper接口中的写法,注意:不要使用参数注解,使用默认的list。
void insetTest(List<Test> list);
xml中的写法。
<insert id="insetTest" useGeneratedKeys="true" keyProperty="id">
insert into test ( name, age) values
<foreach collection="list" item="item" separator=",">
( #{item.name} , #{item.age})
</foreach>
</insert>
希望方面对大家有帮助。。