MyBatis之动态sql

1.Mybatis动态sql是基于OGNL的表达式,可以使我们方便的在sql语句中实现某些逻辑。

2.使用if+where实现多条件查询

1〉dao层方法

 //if动态sql查询
    public List<User> findByIf(User user);

2〉xml配置文件的sql语句

    <!-- if动态sql查询 -->
    <select id="findByIf" resultType="User">
        SELECT  * FROM  user
        <where>
            <if test="userName != null">
                and userName like concat(‘%‘,#{userName},‘%‘)
            </if>

            <if test="userPassword != null">
                and userPassword=#{userPassword}
            </if>
        </where>
    </select>

3〉测试方法

  //if动态sql查询
    @Test
    public  void  findByIf(){
        SqlSession sqlSession = null;
        User user = new User();
        user.setUserName("测");
        //]user.setUserPassword("");
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            List<User> list = sqlSession.getMapper(IUserDao.class).findByIf(user);
            sqlSession.commit();
            for (User user1 : list) {
                System.out.println("user-------->"+user1.getUserCode()+"\t" +user1.getUserName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }

    }

3.choose,相当于java中的switch,通常与otherwise搭配

1〉dao层方法

//智能标签choose查询
    public List<User> findByChoose(User user);

2〉xml配置文件中的sql语句

    <!--choose动态sql查询-->
    <select id="findByChoose" resultType="User">
        SELECT  * FROM  user
        <where>
            <choose>
                <when test="userName!=null">
                    and userName like concat(‘%‘,#{userName},‘%‘)
                </when>
                <when test="userPassword !=null">
                    and userPassword=#{userPassword}
                </when>
                <otherwise></otherwise>
            </choose>
        </where>
    </select>

3〉测试方法

   //choose动态sql查询
    @Test
    public  void  findByChoose(){
        SqlSession sqlSession = null;
        User user = new User();
        user.setUserName("测");
        //]user.setUserPassword("");
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            List<User> list = sqlSession.getMapper(IUserDao.class).findByChoose(user);
            sqlSession.commit();
            for (User user1 : list) {
                System.out.println("user-------->"+user1.getUserCode()+"\t" +user1.getUserName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }

    }

4. (1)foreach:迭代一个集合,通常用于in条件------------->传入数组  array

1〉dao层方法

//智能标签foreach查询 String [] array
    public List<User> findByForeach(String [] depIds);

2〉xml配置文件的sql语句

    <!--foreach动态sql查询 String [] array-->
    <select id="findByForeach" resultType="User">
        SELECT  * FROM  user WHERE  depId in
        <foreach collection="array" open="(" close=")" separator="," item="depIds">
            #{depIds}
        </foreach>
    </select>

3〉测试方法

 //foreach动态sql查询   array
    @Test
    public  void  findByForeach(){
        SqlSession sqlSession = null;
        String [] depIds = {"1","2"};
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            List<User> list = sqlSession.getMapper(IUserDao.class).findByForeach(depIds);
            sqlSession.commit();
            for (User user1 : list) {
                System.out.println("user-------->"+user1.getUserCode()+"\t" +user1.getUserName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }

    }

(2)foreach传入集合----------->list

1〉dao方法

//智能标签foreach查询 List<User> list
    public  List<User> findByForeachList(List<Integer> list);

2〉xml文件的配置

    <!--foreach动态sql查询 Liat<User> list-->
    <select id="findByForeachList" resultType="User">
        SELECT  * FROM  user WHERE  depId in
        <foreach collection="list" open="(" close=")" separator="," item="depIds">
            #{depIds}
        </foreach>
    </select>

3〉测试方法

  //foreach动态sql查询   list
    @Test
    public  void  findByForeachList(){
        SqlSession sqlSession = null;
       List<Integer> list = new ArrayList<Integer>();
       list.add(1);
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            List<User> list1 = sqlSession.getMapper(IUserDao.class).findByForeachList(list);
            sqlSession.commit();
            for (User user3 : list1) {
                System.out.println("user-------->"+user3.getUserCode()+"\t" +user3.getUserName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }

    }
时间: 2024-08-26 09:56:09

MyBatis之动态sql的相关文章

MyBatis的动态SQL详解

MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力.如果你有使用 JDBC 或其他 相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么的痛苦,确保不能忘了空 格或在列表的最后省略逗号.动态 SQL 可以彻底处理这种痛苦. 通常使用动态SQL不可能是独立的一部分,MyBatis当然使用一种强大的动态SQL语言来改进这种

Mybatis的动态Sql

基础部分可以查看我的另一篇博客:http://blog.csdn.net/elim168/article/details/40622491 MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) trim where set foreach if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择.先来看如下一个例子: Xml代码 <sele

mybatis 使用动态SQL

RoleMapper.java public interface RoleMapper { public void add(Role role); public void update(Role role); public void delete(Role role); public List<Role> getRoleList(Role role); } RoleMapper.xml <?xml version="1.0" encoding="UTF-8&

MyBatis中动态SQL语句完成多条件查询

http://blog.csdn.net/yanggaosheng/article/details/46685565 MyBatis中动态SQL语句完成多条件查询 <select id="queryEmp"  resultType="cn.test.entity.Emp"> select * from emp where 1=1 <if test="deptNo!=null"> and deptno=#{deptNO} &

MyBatis 构造动态 SQL 语句

以前看过一个本书叫<深入浅出 MFC >,台湾 C++ 大师写的一本书.在该书中写道这样一句话,"勿在浮沙筑高台",这句话写的的确对啊.编程很多语言虽然相同,但是真正做还是需要认真的学习,如果只是想着按想像着来,真的是会走很多弯路,浪费很多时间. 无法使用 not in 在项目中需要使用到 not in ,想着不是很复杂,但是这个问题困扰了我个把小时,很是郁闷.自己拼接好了字符串,字符串的内容是 not in 中的各个 id 值.通过 not in 来进行 update 的

MyBatis探究-----动态SQL详解

1.if标签 接口中方法:public List<Employee> getEmpsByEmpProperties(Employee employee); XML中:where 1=1必不可少 <select id="getEmpsByEmpProperties" resultType="com.mybatis.entity.Employee"> select * from t_employee where 1=1 <if test=&

Mybatis系列---动态SQL

问题: 什么是动态SQL? 动态SQL有什么作用? 传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误.Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach,可组合成非常灵活的SQL语句,从而提高开发人员的效率. 下述可知道这四个操作节点中的子节点都是差不多是一样的,insert和update中多了一个selectK

一分钟带你了解下MyBatis的动态SQL!

MyBatis的强大特性之一便是它的动态SQL,以前拼接的时候需要注意的空格.列表最后的逗号等,现在都可以不用手动处理了,MyBatis采用功能强大的基于OGNL的表达式来实现,下面主要介绍下. 一.if标签 if是最常用的判断语句,主要用于实现某些简单的条件选择.基本使用示例如下: <select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User&quo

Mybatis的动态sql拼接语句

Mybatis的动态sql拼接语句 1.主配置文件SqlMapConfig.xml  <?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE configuration         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"         "http://mybatis.org/dtd/mybatis-3-config.dtd

mybatis入门-动态sql

什么是动态sql 判断的动态sql mybatis核心就是对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接.组装. 现有需求如下:需要查询用户,输入的是用户类,如果用户的性别类不为空,则将性别作为查询条件之一,如果用户的姓名不为空,则将用户姓名作为查询条件之一.如果用户两个属性都为空,则查询所有用户. 我们知道,在mapper中,我们的传入参数只有一个,多个参数只能通过包转类来实现,现在这种问题怎么解决呢?答案就是在xml文件中加入判断,使sql语句动态生成.刚才的需求所对应的