Mapper.xml中SQL语句的用法示例

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.softcn.mapper.EmpMapper">
    
<select id="getPageEmp" resultType="top.softcn.pojo.Emp">
    select emp.*,dept.name deptName from emp left join dept on emp.dept_id = dept.id
    <where>
        <if test="name != null and name != ''">
            and emp.name like concat('%',#{name},'%')
        </if>
        <if test="gender != null">
            and emp.gender = #{gender}
        </if>
        <if test="begin != null and end != null">
            and emp.entry_date between #{begin} and #{end} ////这里所有参数都千万不要误写成param.begin 等形式
        </if>
    </where>
    order by emp.update_time desc
</select>

</mapper>

 

 

    <!--更新文章-->
    <update id="updateEssay">
        update 表名
        <set>
            <if test="name != null">name = #{name},</if>
            <if test="type != null">type = #{type},</if>
            <if test="status != null">status = #{status},</if>
            ....
        </set>
        where id = #{id}
    </update>
  • 批量删除
    场景:批量删除操作,通常前端会传过来一组ID集合/数组,需要我们根据这一组ID批量删除数据库中对应的记录。
    <!--根据ID批量删除文章-->
    <delete id="deleteEssaysById">
        delete from 表名 where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>

 

collection:集合/数组名,名称要与Mapper类中对应方法的形参名一致;

item:表示集合/数组中的每一位元素的名称,即下面语句中#{}内表示的内容;

separator:表示元素之间的间隔符;

open:表示以下语句以什么开头;

close:表示以下语句以什么结尾;

通过这种方式,拼接出来的内容,实际上就是语句 “delete from 表名 where id in” 后面的内容。如,delete from essay where id in (1,2,3)

  • 批量添加
    场景:因为业务中一对多的关系非常普遍,在添加一条记录(一的一方)时,同时需要将该对象中的对象集合(多的一方)批量添加到对应的数据库表中。比如添加一条教师记录,需要同时添加多条学生记录,表示该教师管理下的多名学生。

在xml文件中,可以这样写:

    <!--批量添加学生-->
    <insert id="insertStudents">
        insert into 学生表名(teacher_id,name,age...) values
        <foreach collection="students" separator="," item="s">
            (#{s.teacher_id},#{s.name},#{s.age}...)
        </foreach>
    </insert>


总结
除了以上四种场景外,可以使用resultMap标签,设置多表查询后的字段名,设置完之后SQL语句查询的结果就可以直接返回封装成一个对象,返回给前端,非常方便

 

posted @ 2025-10-02 13:33  休玛  阅读(5)  评论(0)    收藏  举报