zoukankan      html  css  js  c++  java
  • Mybatis动态SQL

    SQL片段、<if>元素

    SQL片段一般基于单表建立,这样SQL片段可重用性才高。SQL片段一般不要包含where条件。引用其他Mapper的SQL片段时,需要在refid属性中加上其他Mapper的namespace属性!

    <!--定义-->
    <sql id="query_user_where">
    	<if test="id!=null and id!=''">
    		and User.id=#{id} 
    	</if>
    	<if test="name!=null and name!=''"> 
    		and User.name=#{name}
    	</if>
    	<if test="age!=null and age!=''"> 
    		and User.age=#{age}
    	</if>
    </sql>
    <!--引用-->
    <include refid="query_user_where"/>
    

    <where>元素

    where元素会自动去除SQL,以and或or开头的关键字。

    <!--定义-->
    <where>
    	<if test="id!=null and id!=''">
    		and User.id=#{id} 
    	</if>
    	<if test="name!=null and name!=''"> 
    		and User.name=#{name}
    	</if>
    <where>
    

    <set>元素

    set元素会自动去除SQL,最后一个逗号。

    <set>
        <if test="id!=null and id!=''">
            User.id=#{id},
        </if>
        <if test="name!=null and name!=''"> 
            User.name=#{name},
        </if>
    </set>
    

    <foreach>元素

    foreach元素用来遍历Array,List,Map,Set对象。

    <select id="selectUser" parameterType="list" resultType="User">
    	select * from user where id in
    	<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
    		#{item}
    	</foreach>
    </select>
    

    <choose>、<when>、<otherwise>元素

    foreach元素用来遍历Array,List,Map,Set对象。

    <select id="select" parameterType="user" resultType="user">
        select * from user where id=#{id}
        <choose>
            <when test="name != null">
                and name = #{name};
            </when>
            <when test="age != 0">
                and age = #{age};
            </when>
            <otherwise>
                or 1 = 1;
            </otherwise>
        </choose>
    </select>
    

    <trim>元素

    trim元素用来处理一些复杂的SQL操作。

    属性 描述
    prefix 给SQL语句拼接的前缀
    suffix 给SQL语句拼接的后缀
    prefixesToOverride 去除SQL语句前面的关键字或者字符
    suffixesToOverride 去除SQL语句后面的关键字或者字符
    <trim prefix="values(" suffix=")" suffixOverrides=",">
        <if test="id != null and id != ''">
            #{id},
        </if>
        <if test="username != null and username != ''">
            #{username},
        </if>
        <if test="age != null and agae != ''">
            #{age},
        </if>
    </trim>
    

    <bind>元素

    通过bind元素,自定义一个上下文变量,这个变量是可以接受参数的。

    <select id="select" parameterType="string" resultType="user">
        <!--name表示输入进来的参数-->
        <bind name="userName" value="'%'+name+'%'">
        select * from user where name like =#{userName}
    </select>
    
  • 相关阅读:
    从json中获取自己想要的属性
    对称加密解密
    springboot 读取resource目录下的文件
    安装nginx 配置了ssl 启动报错
    复利计算--4.0 单元测试之JAVA版-软件工程
    《构建之法》前三章读后感
    单利 复利计算器程序1.0 2.0 3.0 [ 合 ] 之 WEB
    操作系统 实验一 命令解释程序的编写
    单利 复利计算器程序1.0 2.0 3.0 [ 合 ] 之 C语言
    统计实验数据 总结实验结果
  • 原文地址:https://www.cnblogs.com/feiqiangsheng/p/11719916.html
Copyright © 2011-2022 走看看