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>
相关推荐
日月云棠7 小时前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840828 小时前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide8 小时前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家9 小时前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java
花花无缺9 小时前
搞懂new 关键字(构造函数)和 .builder() 模式(建造者模式)创建对象
java
用户908324602739 小时前
Spring Boot + MyBatis-Plus 多租户实战:从数据隔离到权限控制的完整方案
java·后端
桦说编程10 小时前
实战分析 ConcurrentHashMap.computeIfAbsent 的锁冲突问题
java·后端·性能优化
爱可生开源社区10 小时前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
大道至简Edward14 小时前
Spring Boot 2.7 + JDK 8 升级到 Spring Boot 3.x + JDK 17 完整指南
spring boot·后端
程序员清风14 小时前
用了三年AI,我总结出高效使用AI的3个习惯!
java·后端·面试