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>
相关推荐
天天摸鱼的java工程师3 分钟前
🚪单点登录实战:同端同账号互踢下线的最佳实践(Java 实现)
java·后端
Kiri霧5 分钟前
Go 结构体
java·开发语言·golang
狂奔小菜鸡6 分钟前
Day29 | Java集合框架之Map接口详解
java·后端·java ee
爱学习的小可爱卢9 分钟前
JavaEE进阶——Spring事务与传播机制实战指南
java·java-ee·事务
-大头.10 分钟前
Java泛型实战:类型安全与高效开发
java·开发语言·安全
周杰伦_Jay10 分钟前
【操作系统】进程管理与内存管理
java·数据库·缓存
TDengine (老段)10 分钟前
使用 deepseek 快速搭建 TDengine IDMP demo
大数据·数据库·科技·ai·时序数据库·tdengine·涛思数据
serendipity_hky14 分钟前
【SpringCloud | 第3篇】Sentinel 服务保护(限流、熔断降级)
java·后端·spring·spring cloud·微服务·sentinel
Kiri霧15 分钟前
Go 切片表达式
java·服务器·golang
漂亮的小碎步丶17 分钟前
【2】Spring Boot自动装配
java·spring boot·后端