Mybatis批量增删改查操作数据

该文章展示了使用MyBatis进行批量数据操作的方法,包括批量查询、插入、更新和删除。示例代码详细说明了如何通过ID列表对Student表进行操作,如按ID批量查询学生信息,批量添加学生记录,批量更新学生分数以及批量删除学生记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

批量查询数据

根据ID集合批量查询数据:

mapper.xml

<select id="selectStudentListByIds" parameterType="java.util.List" resultMap="StudentResult">
    SELECT *
    FROM student
    <where>
        id IN
        <foreach item="item" index="index" collection="list"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
        </where>
</select>

mapper.java

@Mapper
public interface StudentMapper extends BaseMapper<Student> {
    List<Student> selectStudentListByIds(List<Integer> list);
}

批量添加数据

向数据表中批量添加多条数据:

mapper.xml

<insert id="batchInsertStudent" parameterType="java.util.List">
    INSERT INTO student(name, gender, age, school, score) VALUES
    <foreach item="item" index="index" collection="list" separator=",">
        (#{item.name},#{item.gender},#{item.age},#{item.school},#{item.score})
    </foreach>
</insert>

mapper.java

@Mapper
public interface StudentMapper extends BaseMapper<Student> {
    void batchInsertStudent(List<Student> list);
}

批量更新数据

批量更新数据表中的多条数据:

mapper.xml

<update id="updateStudentScore" parameterType="java.util.List">
    UPDATE student
    SET score =
    CASE
    <foreach item="item" index="index" collection="list" separator=" ">
        WHEN id = #{item.id} THEN #{item.score}
    </foreach>
    ELSE score
    END
</update>

mapper.java

@Mapper
public interface StudentMapper extends BaseMapper<Student> {
    void updateStudentScore(List<StudentScore> list);
}

批量删除数据

根据ID集合批量删除数据:

mapper.xml

<delete id="deleteStudentByIds" parameterType="java.util.List">
    DELETE FROM student WHERE id IN
    <foreach item="item" index="index" collection="list"
             open="(" separator="," close=")">
        #{item}
    </foreach>
</delete>

mapper.java

@Mapper
public interface StudentMapper extends BaseMapper<Student> {
    void deleteStudentByIds(List<Integer> list);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值