MyBaits中的动态sql

流程示意图
在这里插入图片描述
关于映射的配置
Mapper映射配置
高级查询类设置

public class UserQuery {
    //关键字 模糊查询
    private String  keyWord;
    //最大年龄
    private Integer maxAge;
    //最小年龄
    private Integer minAge;

    @Override
    public String toString() {
        return "UserQuery{" +
                "keyWord='" + keyWord + '\'' +
                ", maxAge=" + maxAge +
                ", minAge=" + minAge +
                '}';
    }

    public String getKeyWord() {
        return keyWord;
    }

    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }

    public Integer getMaxAge() {
        return maxAge;
    }

    public void setMaxAge(Integer maxAge) {
        this.maxAge = maxAge;
    }

    public Integer getMinAge() {
        return minAge;
    }

    public void setMinAge(Integer minAge) {
        this.minAge = minAge;
    }
}

DomainMapper.xml 配置的区别

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
	这个Mapper的主要功能就是写sql
	mapper:根
	namespace:命令空间 (用来确定唯一) 以前这个是可以不加的,现在必需加
     namespace的值,规则的:映射文件XxxMapper.xml所在的包+domain类名+Mapper
 -->
    <!--写domainMapper的绝对路径-->
<mapper namespace="cn.shuhan._03topFind.UserMapper">
    <!--id 要跟接口方法一样
    List<User> topFind(UserQuery query);
    -->
    <!--foreach遍历list
        collection=""  就是数据 就用list
        close="" 以什么结束
        index="" 下标
        item="" 遍历得到的对象
        open="" 以什么开始
        separator="" 分隔符
    -->
    <!--concat(,,) 拼接concat('%',#{keyWord},'%')-->
    <!--<select id="topFind" parameterType="cn.shuhan._03topFind.UserQuery"
            resultType="cn.shuhan._03topFind.User">

        select * from user where name like concat('%',#{keyWord},'%')
    </select>-->
    <!--where标签:能够自动消除第一个的and 和or  要是里面没有内容就不展示where    -->
    <!--<![CDATA[数据]]>  <![CDATA[]]>  中的数据原样输出-->
    <select id="topFind" parameterType="cn.shuhan._03topFind.UserQuery"
            resultType="cn.shuhan._03topFind.User">

        select * from user
        <where>
          <if test="keyWord!=null and keyWord!=''">
              and name like concat('%',#{keyWord},'%')
          </if>
          <if test="maxAge!=null">
              and age <![CDATA[<=]]> #{maxAge}
          </if>
          <if test="minAge!=null">
              and age <![CDATA[>=]]> #{minAge}
          </if>

        </where>
    </select>
</mapper>

总结: 高级查询就是一般条件查询,条件封装成一个类提供get/set ,在Mapper.xml中拼接sql的时候注意if / where / foreach 等的使用

foreach中的属性

where使用
使用:
使用

发布了4 篇原创文章 · 获赞 2 · 访问量 527

猜你喜欢

转载自blog.csdn.net/weixin_43204812/article/details/84997445