zoukankan      html  css  js  c++  java
  • mabatis--动态sql

    1、mybatis核心,对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装;

    2、使用if判断:

    <where>
        <if test="customer!=null">
            <if test="customer.email!=null and customer.email!=''">
                and email like '%${customer.email}%'
            </if>
            <if test="customer.name!=null and customer.name!=''">
                and name like '%${customer.name}%'
            </if>
        </if>
    </where>

    3、sql片段:可以将sql语句语句中的某一片段提取出来,供其他statement引用:

    <!-- 在sql片段中尽量不要使用<where></where>,因为一个statement可以引用多个sql片段,
    若在sql片段中写入了<where></where>,则有可能出现sql语句拼接语法的错误 -->
    <sql id="find_customer_where">
        <if test="customer!=null">
            <if test="customer.email!=null and customer.email!=''">
                and email like '%${customer.email}%'
            </if>
            <if test="customer.name!=null and customer.name!=''">
                and name like '%${customer.name}%'
            </if>
        </if>
    </sql>
    
    <!-- 引用sql片段 -->
    <select id="findCustomerList" parameterType="CustomerQueryVo" resultType="Customer">
        select * from customers
        <where>
            <include refid="find_customer_where"></include>
        </where>    
    </select>

    4、foreach: 

    <sql id="find_customer_foreach">
        <if test="ids!=null">
            <!-- select * from customer where (id=1 or id=2 or id=5)-->
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
            </foreach>
            <!-- select * from customer where id in (1, 2, 5) -->
            <!-- <foreach collection="ids" item="id" open="and id in(" close=")" separator=",">
            #{id}
            </foreach> -->
        </if>
    </sql>
  • 相关阅读:
    二进制显示整数
    测试intel 8.0
    实用的免费网络空间
    tcp/ip入门(转)
    桶排序
    在talking bar的留言(够无聊)
    重装系统手记
    几个宏
    组合算法<转>
    记深圳慧通面试
  • 原文地址:https://www.cnblogs.com/tengtao93/p/5109825.html
Copyright © 2011-2022 走看看