MyBatis对PostgreSQL批量新增并设置主键序列自增
问题梳理:
项目是用若依搭的架子,原先是使用MySQL数据库,使用的是Mybatis
后面由于需求变化现在要切换到PostgreSQL数据库
在数据库切换时,虽然都是关系型数据库,但是差别却十分之大
相关参考文档
有关修改相关配置的,可以参考这篇博客
链接: Ruoyi从mysql切换到postgresql的几个坑
有关修改语法的,可以参考这篇博客(这个里面有修改表的对应SQL文件)
链接: 使用ruoyi集成postgresql数据库快速爬坑
正题
1.首先创建库表所对应的自增序列,运行写好的SQL
create sequence public.t_table_id_seq
increment 1
start 1
minvalue 1
maxvalue 99999999
cache 1;
#然后添加给对应字段
alter table public.t_table alter column table_id set default nextval('public.t_table_id_seq');
2.然后修改我们的xml文件,这里我写了一个批量新增和一个新增方法
<!--批量新增-->
<insert id="batchInsert">
insert into t_table(id,name,direction,desc)
VALUES
<foreach collection="list" item="param" index="index" separator=",">
(
nextval('t_table_id_seq'),
#{param.name},
#{param.direction},
#{param.desc}
)
</foreach>
</insert>
<!--普通新增-->
<insert id="insert" parameterType="Param" useGeneratedKeys="true" keyProperty="id">
<selectKey keyProperty="id" resultType="java.lang.Long" order="AFTER">
SELECT nextval('t_table_id_seq')
</selectKey>
insert into t_table
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null and id != 0">id,</if>
<if test="name!= null and name != ''">name,</if>
<if test="direction != null and direction!= ''">direction,</if>
<if test="desc!= null and desc!= ''">desc,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null and id != 0"> #{id},</if>
<if test="name != null and name != ''"> #{name},</if>
<if test="direction != null and direction != ''"> #{direction},</if>
<if test="desc != null and desc != ''"> #{desc},</if>
</trim>
</insert>
3.对于批量新增可以继续修改
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
@Override
public void getAndInsertData(Date startTime, Date endTime) {
// 执行批量新增操作
try (SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession()) {
ConflictDataMapper mapper = sqlSession.getMapper(ConflictDataMapper.class);
for (Param param: list) {
List<???> list = getData(???.getCode(), startTime, endTime);
if (list.size() != 0){
mapper.insert(list);
}
}
sqlSession.commit();
}
}
然后就大功告成了!!!