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>