Mybatis动态sql之choose、when、otherwise

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用,它有点像 Java 中的 switch 语句。

  1. 接口类
//按照不同的需求查询
    List<Blog> queryBlogChoose(Map map);
  1. Mapper.xml配置文件
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <choose>
                <when test="title!=null">
                    title=#{title}
                </when>
                <when test="author!=null">
                    and author=#{author}
                </when>
                <otherwise>
                    1=1
                </otherwise>
            </choose>
        </where>
    </select>
  1. 测试类
public class Test {
    
    
    @org.junit.Test
    public void test(){
    
    
        //通过封装好的工具类获取SqlSession会话
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //通过接口类型class获取接口对象实例(动态代理)
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        //执行接口中的方法
        HashMap<String,Object> map=new HashMap<String, Object>();
        //map.put("title","Java如此简单");
        //map.put("author","chenhui");
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog : blogs) {
    
    
            System.out.println(blog);
        }
        sqlSession.commit();
        //关闭SqlSession
        sqlSession.close();
    }
}

如果未传值,由于choose中有otherwise元素,则where子句会执行,即使when元素都不满足都会执行otherwise语句,因此可以通过条件otherwise来查询结果
在这里插入图片描述

如果传值时,它会按照choose元素中的when元素顺序书写进行执行一种情况,如果传入title,则它不会执行其他条件,即使其他条件都满足都不会执行

在这里插入图片描述

其他条件满足时,也会执行when元素条件成立的第一个语句

public class Test {
    
    
    @org.junit.Test
    public void test(){
    
    
        //通过封装好的工具类获取SqlSession会话
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //通过接口类型class获取接口对象实例(动态代理)
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        //执行接口中的方法
        HashMap<String,Object> map=new HashMap<String, Object>();
        map.put("title","Java如此简单");
        map.put("author","chenhui");
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog : blogs) {
    
    
            System.out.println(blog);
        }
        sqlSession.commit();
        //关闭SqlSession
        sqlSession.close();
    }
}

在这里插入图片描述

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

猜你喜欢

转载自blog.csdn.net/weixin_45608165/article/details/113748341
今日推荐