1.IF标签

需求:根据条件查询用户

  在Mapper.xml中编写

    <!-- 根据sex和username查询user -->
    <select id="findbySexandUsername" parameterType="User" resultType="User">
        select * from user where sex = #{sex} and username = #{username}
    </select>

  问题:当传入的参数中缺少需要的属性时,不能查出信息

使用IF标签解决:

    <!-- 根据sex和username查询user -->
    <select id="findbySexandUsername" parameterType="User" resultType="User">
        select * from user
        where 1=1
        <if test="sex!=null and sex!='' ">
            and sex = #{sex}
        </if>
        <if test="username!=null and username!='' ">
            and username = #{username}
        </if>
    </select>

2.WHERE标签

  问题:上面的IF标签 中 Where 1=1 显得很麻烦

使用where解决

    <!-- 根据sex和username查询user -->
    <select id="findbySexandUsername" parameterType="User"
        resultType="User">
        select * from user
        <!-- where标签可以自动添加where,同时处理sql语句中第一个and关键字 -->
        <where>
            <if test="sex!=null and sex!='' ">
                and sex = #{sex}
            </if>
            <if test="username!=null and username!='' ">
                and username = #{username}
            </if>
        </where>

    </select>
where标签可以自动添加where,同时处理sql语句中第一个and关键字

3.SQL标签

  问题:在一个Mapper.xml中有许多重复的语句

使用SQL标签解决

    <!-- 查询所有的orders -->
    <select id="findAllOrders" resultMap="ordersResultMap">
        select * from orders
    </select>

    <!-- 声明sql片段 -->
    <sql id="selectUser">
        select * from user
    </sql>

    <!-- 根据sex和username查询user -->
    <select id="findbySexandUsername" parameterType="User" resultType="User">

        <include refid="selectUser"/>

        <!-- where标签可以自动添加where,同时处理sql语句中第一个and关键字 -->
        <where>
            <if test="sex!=null and sex!='' ">
                and sex = #{sex}
            </if>
            <if test="username!=null and username!='' ">
                and username = #{username}
            </if>
        </where>

    </select>

  如果要使用别的namespace中的sql标签,在refid中加入namespace名字

4.FOREACH

  当查询需要用到in时。例如:根据多个id查询用户信息

  需要通道foreach标签

1.数组

接口

    /**
     * 根据ids来查询
     */
    public List<User> findByIds(int[] ids);

映射

    <!-- 根据ids来查询 -->
    <select id="findByIds" parameterType="int[]" resultType="User">
        select * from user
        where
        id in
        <!-- foreach标签,进行遍历 -->
        <!-- collection:遍历的集合 -->
        <!-- item:遍历的项目,可以随便写,,但是和后面的#{}里面要一致 -->
        <!-- open:在前面添加的sql片段 -->
        <!-- close:在结尾处添加的sql片段 -->
        <!-- separator:指定遍历的元素之间使用的分隔符 -->
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

测试

    /**
     * 根据ids
     */
    @Test
    public void m05() {
        // 获取sqlSession,和Spring整理后由Spring管理
        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        // 从sqlSession中获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        // 执行查询
        int[] ids = new int[3];
        ids[0] = 10;
        ids[1] = 16;
        ids[2] = 22;

        List<User> list = userMapper.findByIds(ids);
        for (User user : list) {
            System.out.println(user);
        }
    }

  注意:这样写会报错

  原因:这种情况映射中的collection必须按照规范写

  ids 改为 array

再次测试:

2.集合

    /**
     * 根据ids
     */
    @Test
    public void m05() {
        // 获取sqlSession,和Spring整理后由Spring管理
        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        // 从sqlSession中获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        // 执行查询
        List<Integer> ids = new ArrayList<>();
        ids.add(10);
        ids.add(16);
        ids.add(22);

        List<User> users = userMapper.findByIds(ids);
        for (User user : users) {
            System.out.println(user);
        }
    }
}
    /**
     * 根据ids来查询
     */
    public List<User> findByIds(List ids);
    <!-- 根据ids来查询 -->
    <select id="findByIds" parameterType="List" resultType="User">
        select * from user
        where
        id in
        <!-- foreach标签,进行遍历 -->
        <!-- collection:遍历的集合,这里是QueryVo的ids属性 -->
        <!-- item:遍历的项目,可以随便写,,但是和后面的#{}里面要一致 -->
        <!-- open:在前面添加的sql片段 -->
        <!-- close:在结尾处添加的sql片段 -->
        <!-- separator:指定遍历的元素之间使用的分隔符 -->
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

  注意:同样不能随意写collection

  应该将 ids 改为 list

05.Mybatis动态sql的更多相关文章

  1. MyBatis 动态SQL(十二)

    动态条件查询 以下是我们数据库表 tb_user 的记录: 假设现在有一个需求,就是根据输入的用户年龄和性别,查询用户的记录信息.你可能会说,这太简单了,脑袋里立马蹦出如下的 SQL 语句: SELE ...

  2. mybatis动态sql以及分页

    1.mybatis动态sql 2.模糊查询 3.查询返回结果集的处理 4.分页查询 5.特殊字符处理 1.mybatis动态sql If.trim.foreach If 标签判断某一字段是否为空 &l ...

  3. mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句

    mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:1. if 语句 (简单的条件判断)2. c ...

  4. 9.mybatis动态SQL标签的用法

    mybatis动态SQL标签的用法   动态 SQL MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么 ...

  5. 自己动手实现mybatis动态sql

    发现要坚持写博客真的是一件很困难的事情,各种原因都会导致顾不上博客.本来打算写自己动手实现orm,看看时间,还是先实现一个动态sql,下次有时间再补上orm完整的实现吧. 用过mybatis的人,估计 ...

  6. Mybatis动态SQL单一基础类型参数用if标签

    Mybatis动态SQL单一基础类型参数用if标签时,test中应该用 _parameter,如: 1 2 3 4 5 6 <select id="selectByName" ...

  7. 超全MyBatis动态SQL详解!( 看完SQL爽多了)

    MyBatis 令人喜欢的一大特性就是动态 SQL. 在使用 JDBC 的过程中, 根据条件进行 SQL 的拼接是很麻烦且很容易出错的. MyBatis 动态 SQL 的出现, 解决了这个麻烦. My ...

  8. Mybatis动态SQL简单了解 Mybatis简介(四)

    动态SQL概况 MyBatis 的强大特性之一便是它的动态 SQL 在Java开发中经常遇到条件判断,比如: if(x>0){ //执行一些逻辑........ }   Mybatis应用中,S ...

  9. mybatis原理分析学习记录,mybatis动态sql学习记录

    以下个人学习笔记,仅供参考,欢迎指正. MyBatis 是支持定制化 SQL.存储过程以及高级映射的持久层框架,其主要就完成2件事情: 封装JDBC操作 利用反射打通Java类与SQL语句之间的相互转 ...

随机推荐

  1. 2019/11/8 CSP模拟

    T1 药品实验 内网#4803 由概率定义,有\[a + b + c = 0\] 变形得到\[1 - b = a + c\] 根据题意有\[p_i = a p _{i - 1} + b p_i + c ...

  2. mac 安装并使用 mysql 或者 mac mysql 忘记密码,Can't connect to local MySQL server through socket homebrew

    1. brew install mysql 2. 启动mysql mysql.server start 我遇到了这个error,查openstack解决,我在这粘一下 ### Error:Can't ...

  3. spring boot jpa没有自动生成表的原因——加上@Entity

    别人的项目弄了好久,竟然是忘记加注解,当然配置文件还是要配置jpa的,pom也要依赖jpa. @Entity jpa: hibernate: ddl-auto: update show-sql: tr ...

  4. 把swf反编译成fla的几种方法

    2007年著 第一种方法: 利用IMPERATOR FLA1.63 ,这个软件有演示版 和正式版 , 演示版不能反编译Action Scropt,在利用正式版反编译的过程中有时会丢失Action Sc ...

  5. AsyncAwait

    using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namesp ...

  6. 剑指offer——36二叉树和为某一值的路径

    题目描述 输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径.路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径.(注意: 在返回值的list中,数组长度大 ...

  7. spring @Transactional注解参数详解(13)

    事物注解方式: @Transactional 当标于类前时, 标示类中所有方法都进行事物处理 , 例子: 1 @Transactional public class TestServiceBean i ...

  8. Neo4j中实现自定义中文全文索引

    数据库检索效率时,一般首要优化途径是从索引入手,然后根据需求再考虑更复杂的负载均衡.读写分离和分布式水平/垂直分库/表等手段:索引通过信息冗余来提高检索效率,其以空间换时间并会降低数据写入的效率:因此 ...

  9. scala 中List的简单使用

    /** * scala 中List的使用 * */ object ListUse { def main(args: Array[String]): Unit = { def decorator(l:L ...

  10. HTML --- 简单的标签

    HTML --- 简单的标签 html概述和基本结构 html概述 HTML是 HyperText Mark-up Language 的首字母简写,意思是超文本标记语言,超文本指的是超链接,标记指的是 ...