Java框架_Mybatis_day05_映射文件之动态SQL

14 篇文章 0 订阅
11 篇文章 0 订阅

目录

九、Mybatis 映射文件之动态SQL

9.1 标签的使用

9.2 标签的使用

9.3 标签的使用

9.4 Mybatis中简化编写的SQL片段 : 标签的使用


九、Mybatis 映射文件之动态SQL

9.1 <if> 标签的使用

<select id="findByCondition" parameterType="user" resultType="user">
    select * from user where 1 = 1
    <if test="username != null">
       and username like #{username}
    </if>
    <if test="sex != null">
       and sex = #{sex}
    </if>
</select>

       <if>标签的test属性中写的是对象的属性名,如果是包装类的对象要使用OGNL表达式的写法,另外要注意where 1=1 的作用。

9.2 <where> 标签的使用

<select id="findByCondition" parameterType="user" resultType="user">
    select * from user
    <where>
        <if test="username != null">
            and username like #{username}
        </if>
        <if test="sex != null">
            and sex = #{sex}
        </if>
    </where>
</select>

注意:<where >可以自动处理第一个and

9.3 <foreach> 标签的使用

这里我们先创建一个QueryVo类来封装一个List集合:

QueryVo.java

package com.cpz.domain;

import java.util.ArrayList;
import java.util.List;

public class QueryVo {
    private User user;
    private List<Integer> ids = new ArrayList<Integer>();

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<Integer> getIds() {
        return ids;
    }

    public void setIds(List<Integer> ids) {
        this.ids = ids;
    }
}

UserDao.xml

<!--4.3 动态SQL标签之<foreach>标签
    collection:使用ognl读取queryVo实体中的集合属性名
    open:sql语句的前缀
    close:sql语句的后缀
    item:遍历集合的每个值的标识
    separator:遍历集合的每个值的分隔符
 -->
<select id="findByCondition2" resultType="user" parameterType="queryVo">
     select * from user
     <where>
        <if test="ids != null and ids.size() > 0">
            <foreach collection="ids" open=" and id in (" close=")" item="id" separator=",">
                #{id}
            </foreach>
        </if>
     </where>
</select>

TestUser.java

public void findByCondition2(){
    List<Integer> ids = new ArrayList<Integer>();
    ids.add(41);
    ids.add(42);
    ids.add(43);
    QueryVo queryVo = new QueryVo();
    queryVo.setIds(ids);
    List<User> list = userDao.findByCondition2(queryVo);
    for (User user : list) {
        System.out.println(user);
    }
}

9.4 Mybatis中简化编写的SQL片段 :<sql> 标签的使用

 

       可以将sql语句中重复的部分提取出来,类似于:select * from user,使用时用include进行引用即可

<sql id="defaultSql">
    select * from user
</sql> 
  
<select id="findByCondition" parameterType="user" resultType="user">
    <include refid="defaultSql"></include>
    <where>
        <if test="username != null">
            and username like #{username}
        </if>
        <if test="sex != null">
            and sex = #{sex}
        </if>
    </where>
</select>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值