Mybatis:Oracle批量新增、批量修改

Oracle批量新增

1、创建 SEQUENCE ,用于自增主键

sql 复制代码
CREATE SEQUENCE  TEST_SEQ
    minvalue 1
    maxvalue 9999999999999999999
    start with 1
    increment by 1
    cache 100;

2、创建实体类,用于存数据

java 复制代码
@Data
@Accessors(chain = true)
public class Student {
    /**
     * 主键(自增用TEST_SEQ)
     */
    private Long id;
    /**
     * 名字
     */
    private String name;
    
}

3、造数据,不用造自增id

java 复制代码
List<Student> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Student student = new Student();
            student.setName(String.valueOf(Math.random()));
            list.add(student);
        }
// 获取自增id
List<Student> studentList = studentMapper.selectBatchidBySequence(list);
// 批量新增
Integer studentResults = studentMapper.insertBatchStudent(mpPointsOpenList);

4、使用 SEQUENCE ,获取自增id

xml 复制代码
    <select id="selectBatchidBySequence" resultType="com.zhao.test.pojo.Student">
        select TEST_SEQ.nextval as id, t.* from (
        <foreach collection="list" index="index" item="item" separator="union all">
            select
            #{item.name,jdbcType=VARCHAR} as name
            from dual
        </foreach>
        )t
    </select>

5、批量新增

xml 复制代码
    <insert id="insertBatchStudent">
        insert into STUDENT (ID,NAME)
        select * from (
        <foreach collection="list" item="item" separator="union all">
            select #{item.id,jdbcType=BIGINT},#{item.name,jdbcType=VARCHAR}
            from dual
        </foreach>
            )
    </insert>

Oracle批量修改

还是用之前的实体类做修改

1、造数据

java 复制代码
List<Student> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Student student = new Student();
            student.setName(String.valueOf(Math.random()));
            // 这里应为数据库有的id
            student.setId((long) (Math.random() * 1000));
            list.add(student);
        }
// 批量修改
Integer studentResults = studentMapper.updateBatchStudent(list);

2、批量修改

xml 复制代码
    <update id="updateBatchStudent">
        <foreach collection="list" item="item" separator=";" open="begin" close=";end;">
            update STUDENT
            <trim prefix="set" suffixOverrides=",">
                <if test="item.name != null">NAME=#{item.name},</if>
            </trim>
            where ID = #{item.id}
        </foreach>
    </update>
相关推荐
陈果然DeepVersion28 分钟前
Java大厂面试真题:Spring Boot+Kafka+AI智能客服场景全流程解析(十)
java·spring boot·ai·kafka·面试题·向量数据库·rag
KYGALYX35 分钟前
在Linux中备份msyql数据库和表的详细操作
linux·运维·数据库
檀越剑指大厂1 小时前
金仓KReplay:定义数据库平滑迁移新标准
数据库
但要及时清醒1 小时前
ArrayList和LinkedList
java·开发语言
努力成为一个程序猿.1 小时前
【Flink】FlinkSQL-动态表和持续查询概念
大数据·数据库·flink
一叶飘零_sweeeet1 小时前
从测试小白到高手:JUnit 5 核心注解 @BeforeEach 与 @AfterEach 的实战指南
java·junit
kali-Myon1 小时前
NewStarCTF2025-Week4-Web
sql·安全·web安全·php·ctf·ssti·ssrf
摇滚侠2 小时前
Spring Boot3零基础教程,Reactive-Stream 四大核心组件,笔记106
java·spring boot·笔记
Z3r4y2 小时前
【代码审计】RuoYi-3.0 三处安全问题分析
java·web安全·代码审计·ruoyi-3.0