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();
        }
	}

然后就大功告成了!!!

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值