mybatis连接postgresql插入后获取序列值

在工作中遇到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>

希望方面对大家有帮助。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值