GenweiWu / Blog

个人技术能力提升
MIT License
4 stars 0 forks source link

postgresql #87

Open GenweiWu opened 2 years ago

GenweiWu commented 2 years ago

RETURNING关键字

常见用法:insert后returning

CREATE TABLE items (
  id SERIAL primary key,
  name varchar,
  created timestamp with time zone default now()
);
INSERT INTO items (name) values ('bear') RETURNING id, created;

结合mybatis的用法

https://github.com/mybatis/mybatis-3/issues/1293

@select("INSERT INTO public.user(name) VALUES(#{name}) RETURNING id")
@options(flushCache = Options.FlushCachePolicy.TRUE)

参考

GenweiWu commented 2 years ago

返回insert的主键id(自增类型)

http://www.tianshouzhi.com/api/tutorials/mybatis/378

<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)

如果是batch插入

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>