• 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>
  • 相关阅读:
    枚举工具类:封装判断是否存在这个枚举
    MYSQL插入emoji报错解决方法Incorrect string value
    文件大小转换带上单位工具类(文件byte自动转KBMBGB)
    mysql 统计七天数据并分组
    mybatis plus 和 druid 版本导致LocalDateTime 不兼容问题
    Layui弹框中select下拉列表赋值回显
    查看环境版本
    Linux 常用命令
    安装jdk14的坑
    modbus_tk解析
  • 原文地址:https://www.cnblogs.com/tengtao93/p/5109825.html
Copyright © 2020-2023  润新知