Mybatis动态SQL IF语句 Mybatis动态SQL之IF语句详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Mybatis动态SQL IF语句 Mybatis动态SQL之IF语句详解

TheLightOfCode   2021-05-06 我要评论
想了解Mybatis动态SQL之IF语句详解的相关内容吗,TheLightOfCode在本文为您仔细讲解Mybatis动态SQL IF语句的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:mybatis动态sql语句,mysql动态sql语句基本语法,mybatis执行动态sql,下面大家一起来学习吧。

Mysql 5.0 以后,支持了动态sql语句,我们可以通过传递不同的参数得到我们想要的值.

1. Mybatis–动态SQL之IF语句

没有搭建环境的请点击

1.1 BlogMapper.java

    //   查询博客
    List<Blog> queryBlogIf(Map map);

1.2 BlogMapper.xml

    <select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from mybatis.blog where 1=1
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </select>

1.3 Test.java

1.3.1 第一种情况,不加任何查询条件,默认会把所有数据查出来

    //    第一种情况,不加任何查询条件,默认会把所有数据查出来
    @org.junit.Test
    public void test01() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap();
        List<Blog> blogs = mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }

运行结果:

查询出了所有记录

1.3.2 第二种情况,添加参数title

    @org.junit.Test
    public void test01() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap();
        map.put("title", "Spring");
        List<Blog> blogs = mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }

查询出了一条记录

1.3.3 第三种情况,添加2个参数

    @org.junit.Test
    public void test01() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap();
        map.put("title", "微服务");
        map.put("author", "天天天");
        List<Blog> blogs = mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们