08【MyBatis之动态SQL】

二、MyBatis之动态SQL

Mybatis 的映射文件中,前面我们的SQL都是比较简单的,有些时候业务逻辑复杂时,我们的 SQL是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了。

2.1 动态SQL之<if>标签

我们根据实体类的不同取值,使用不同的SQL语句来进行查询。比如在 id 如果不为空时可以根据 id查询,如果name不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。

  • 接口:
Emp findByIdAndName(@Param("id") Integer id, @Param("name") String name);
  • mapper.xml:
<?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="com.dfbz.dao.EmpDao">
    <select id="findByIdAndName" resultType="emp">
        select * from emp where 1=1
        <if test="id!=null">
            and id=#{id}
        </if>
        <if test="name!=null">
            and name=#{name}
        </if>
    </select>
</mapper>
  • 测试类:
package com.dfbz.test;

import com.dfbz.dao.EmpDao;
import com.dfbz.entity.Condition;
import com.dfbz.entity.Emp;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */

public class Demo01 {

    private SqlSessionFactory factory;
    private SqlSession session;

    @Before
    public void before() throws IOException {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        factory = builder.build(is);
        session = factory.openSession(true);     
    }

    @After
    public void after() throws IOException {          
        session.close();
    }

    @Test
    public void test1() throws Exception{
        Emp emp = empDao.findByIdAndName(1, "张三");
        System.out.println(emp);
    }
}

2.2 动态 SQL 之<where>标签

为了简化上面 where 1=1 的条件拼装,我们可以采用<where>标签来简化开发。

<?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="com.dfbz.dao.EmpDao">
   <select id="findByIdAndName" resultType="emp">
        select * from emp
        <where>
            <if test="id!=null">
                and id=#{id}
            </if>
            <if test="name!=null">
                and name=#{name}
            </if>
        </where>
    </select>
</mapper>

Tips:where只能帮我们去除前and,不能帮助我们去除后and(where标签除了可以智能的去除and,也可以智能的去除or)

2.3 动态标签之<foreach>标签

我们在进行范围查询时,就要将一个集合中的值,作为参数动态添加进来。这样我们将如何进行参数的递?

MyBatis在传递集合时,将集合的key设置为:collection(List集合、Set集合等),在mapper.xml中,使用#{collection}就可以获取到集合的值,如果是List类型的集合,还可以使用#{list}来获取到集合的值,如果是数组类型,那么需要使用#{array}来获取值

2.3.1 传递List集合

  • dao接口:
List<Emp> findByIds(List<Integer> ids);
  • mapper.xml:
<!--
    foreach:
        collection: 遍历的集合
        item:每次遍历的临时值
        separator:分隔符
        open:遍历之前加上的符号
        close:遍历之后加上的符号
-->
<select id="findByIds" resultType="emp">
    select * from emp
    <where>
        <!-- 使用list或collection获取集合的值 -->
        <if test="list!=null and collection.size>0">
            id in 
            <foreach collection="list" item="id" separator="," open="(" close=")">
                #{id}
            </foreach>
        </if>
    </where>
</select> 
  • 测试:
@Test
public void test2() {
    //创建id
    List<Integer> ids = Arrays.asList(1, 2, 3);

    List<Emp> empList = empDao.findByIds(ids);
    for (Emp emp : empList) {
        System.out.println(emp);
    }
}

2.3.2 传递Set和数组

  • dao接口:
List<Emp> findByIds2(Set<Integer> ids);

List<Emp> findByIds3(Integer[] ids);
  • mapper.xml:
<select id="findByIds2" resultType="emp">
    select * from emp
    <where>
        <!-- set集合只能用collection -->
        <if test="collection!=null and collection.size>0">
            id in
            <foreach collection="collection" item="id" separator="," open="(" close=")">
                #{id}
            </foreach>
        </if>
    </where>
</select>

<select id="findByIds3" resultType="emp">
    select * from emp
    <where>
        <!-- 数组只能用array(注意:数组没有size方法,只有length属性!) -->
        <if test="array!=null and array.length>0">
            id in
            <foreach collection="array" item="id" separator="," open="(" close=")">
                #{id}
            </foreach>
        </if>
    </where>
</select>
  • 测试类:
@Test
public void test3() {

    HashSet<Integer> ids = new HashSet<>(Arrays.asList(1, 2, 3));

    List<Emp> empList2 = empDao.findByIds2(ids);
    List<Emp> empList3 = empDao.findByIds3(new Integer[]{1,2,3});

    System.out.println(empList2);
    System.out.println(empList2);
}

2.4 <choose>组合标签

choose 相当于 java 里面的 switch 语句。otherwise(其他情况)

  • dao接口:
List<Emp> findByEmp(Emp emp);
  • 测试类:
@Test
public void test4() {

    Emp emp = new Emp();
    emp.setId(1);
    emp.setName("张%");

    List<Emp> empList = empDao.findByEmp(emp);

    System.out.println(empList);
}
  • mapper.xml:
<select id="findByEmp" resultType="emp">
    select * from emp
    <where>
        <choose>
            <when test="id!=null">
                and id=#{id}
            </when>
            <when test="name!=null">
                and name like #{name}
            </when>
            <otherwise>
                and 1!=1
            </otherwise>
        </choose>
    </where>
</select>
  • 测试类:
@Test
public void test4() {

    Emp emp = new Emp();
    emp.setId(1);
    emp.setName("张%");

    List<Emp> empList = empDao.findByEmp(emp);

    System.out.println(empList);
}

2.5 <set>标签

set标签和where标签很类似,set标签主要是用在更新操作的时候,如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。

  • dao接口:
void update(Emp emp);
  • mapper.xml:
<update id="update">
    update emp
    <set>
        <if test="name != null">
            name = #{name},
        </if>
        <if test="age != null">
            age = #{age},
        </if>
        <if test="addr != null">
            addr = #{addr},
        </if>
        <if test="salary != null">
            salary = #{salary},
        </if>
    </set>
    where id=#{id}
</update>
  • 测试类:
@Test
public void test5() {

    empDao.update(new Emp(1,"张三三",null,null,null));
}

Tips:与where标签不同的是,set标签能够去除多余的前后,

2.6 <trim>标签

trim标签的作用和where标签类似,不过trim标签可以定制化去除的内容和增加的内容,where标签只能增加where,去除and、or等;

  • trim标签使用说明:
属性说明
prefix给SQL语句拼接的前缀
suffix给SQL语句拼接的后缀
prefixOverrides去除的前缀
suffixOverrides去除的后缀

2.6.1 去除前缀

  • dao接口:
List<Emp> findByIdOrName(@Param("id") Integer id,@Param("name") String name);
  • mapper.xml:
<select id="findByIdOrName" resultType="emp">
    select * from emp

    <!--
        prefix: 如果trim标签内的内容有一个成立,那么增加where前缀
        prefixOverrides: 去除前面拼接的and 或者 or 使得SQL语法正确
     -->
    <trim prefix="where" prefixOverrides="and|or">
        <if test="id!=null">
            or id = #{id}
        </if>
        <if test="name!=null">
            or name = #{name}
        </if>
    </trim>
</select>
  • 测试:
@Test
public void test6() {
    List<Emp> empList = empDao.findByIdOrName(1, "张三");
    System.out.println(empList);
}

2.6.2 去除后缀

  • dao接口:
void update2(Emp emp);
  • mapper.xml:
<update id="update2" parameterType="Emp">
    update emp
    <trim prefix="set" suffixOverrides=",">
        <if test="name != null">
            name = #{name},
        </if>
        <if test="age != null">
            age = #{age},
        </if>
        <if test="addr != null">
            addr = #{addr},
        </if>
        <if test="salary != null">
            salary = #{salary},
        </if>
    </trim>
    where id=#{id}
</update>
  • 测试:
@Test
public void test7() {
    empDao.update(new Emp(1, "张三三", null, null, null));
}

2.6.3 定义前后缀

  • dao接口:
void save(Emp emp);
  • mapper.xml:
<insert id="save" parameterType="Emp">
    insert into emp
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="id!=null">
            id,
        </if>
        <if test="name!=null">
            name,
        </if>
    </trim>

    values
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="id!=null">
            #{id},
        </if>
        <if test="name!=null">
            #{name},
        </if>
    </trim>
</insert>
  • 测试:
@Test
public void test8() {
    empDao.save(new Emp(11,"小陈",null,null,null));
}

2.7 定义SQL片段

Sql 中可将重复的 sql提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的。我们先到EmpDao.xml文件中使用<sql>标签,定义出公共部分,如下:

<sql id="findEmp">
    select * from emp
</sql>

<select id="findByIds" resultType="emp">
    <include refid="findEmp"></include>
    <where>
        <if test="collection!=null and collection.size>0">
            id in
            <foreach collection="collection" item="id" separator="," open="(" close=")">
                #{id}
            </foreach>
        </if>
    </where>
</select>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

緑水長流*z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值