持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第9天,点击查看活动详情
动态sql
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。
1. < sql>标签
当多种类型的查询语句的查询字段或者查询条件相同时,可以将其定义为常量,方便调用。
<!--定义列名-->
<sql id="columns">\
id,username,birthday,sex,address\
</sql>
<!--定义条件-->
<sql id="Example_Where_Clause" >\
<where >\
<foreach collection="oredCriteria" item="criteria" separator="or" >\
<if test="criteria.valid" >\
<trim prefix="(" suffix=")" prefixOverrides="and" >\
<foreach collection="criteria.criteria" item="criterion" >\
<choose >\
<when test="criterion.noValue" >\
and ${criterion.condition}\
</when>\
<when test="criterion.singleValue" >\
and ${criterion.condition} #{criterion.value}\
</when>\
<when test="criterion.betweenValue" >\
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}\
</when>\
<when test="criterion.listValue" >\
and ${criterion.condition}\
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >\
#{listItem}\
</foreach>\
</when>\
</choose>\
</foreach>\
</trim>\
</if>\
</foreach>\
</where>\
</sql>
2. < include>标签
用于引用定义的常量。
<!--引用定义的列名-->
select <include refid="columns"></include>\
from users
<!--引用定义的条件-->
<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.bjpowernode.pojo.ProductInfoExample" >\
select\
<if test="distinct" >\
distinct\
</if>\
<include refid="Base_Column_List" />\
from product_info\
<if test="_parameter != null" >\
<include refid="**Example_Where_Clause**" />\
</if>\
<if test="orderByClause != null" >\
order by ${orderByClause}\
</if>\
</select>
3. < if>标签
进行条件判断。
<if test="userName != null and userName != '' ">\
and username like concat('%',#{userName},'%')\
</if>
4. < where>标签
一般开发复杂业务的查询条件时,如果有多个查询条件,通常会使用< where>标签来进行控制。 标签可以自动的将第一个条件前面的逻辑运算符 (or ,and) 去掉,正如代码中写的,id 查询条件前面是有“and”关键字的,但是在打印出来的 SQL 中却没有,这就是< where> 的作用。
<select id="getByCondition" resultType="users" parameterType="users">\
select <include refid="allColumns"></include>\
from users\
<where>\
<if test="userName != null and userName != '' ">\
and username like concat('%',#{userName},'%')\
</if>\
<if test="birthday != null ">\
and birthday = #{birthday}\
</if>\
<if test="sex != null and sex !=''">\
and sex = #{sex}\
</if>\
<if test="address != null and address !=''">\
and address like concat('%',#{address},'%')\
</if>\
</where>\
</select>
测试
@Test\
public void testGetByCondition()throws Exception{\
Users u = new Users();\
u.setUserName("小");\
u.setSex("1");\
u.setAddress("市");\
u.setBirthday(sf.parse("2002-01-19"));\
List<Users> list = usersMapper.getByCondition(u);\
list.forEach(users -> System.*out*.println(users));\
}
运行结果: