目录
一、MyBatis之动态SQL
1.1MyBatis动态SQL概述
1).动态SQL,通过MyBatis 提供的各种标签对条件作出判断以实现动态拼接SQL 语句,主要是where部分有变化。
2).常用的动态SQL 标签有<if>、<where>、<sql/>、<foreach>等。
3).MyBatis 的动态SQL 语句,与JSTL标签中的语句非常相似。
4).动态 SQL应用场景:
主要用于解决查询条件不确定的情况。
在程序运行期间,根据用户提交的查询条件进行查询。
提交的查询条件不同,执行的 SQL 语句不同。
若将每种可能的情况都由程序员逐一列出,
对所有条件进行排列组合,将会出现大量的SQL 语句。
此时,可使用动态 SQL 来解决这样的问题。
5).注意,动态sql的sql语句部分可以使用 ">"和">=",但是不能使用 "<"和"<=",要使用 "<" 表示 "<","<="表示 "<="(验证:查询指定价格范围内的数据)。> >
1.2 动态SQL之<if>+<where>
<select id="selectIdOrName" resultType="com.zking.model.User">
select <include refid="Base_Column_List"/>
from tb_user where true
<if test="null != userId and '' != userId">
and user_id = #{userId}
</if>
<if test="null != userName and '' != userName">
or user_name = #{userName}
</if>
</select>
test类
@Test
public void selectIdOrName(){
System.out.println(userService.selectIdOrName(1, "李四"));
}
1.3 动态sql之trim
属性:
prefix:要添加的前缀;prefixOverrides:要删除的前缀。
suffix:要添加的后缀;suffixOverrides:要删除的后缀。
<insert id="insertSelective" parameterType="com.zking.model.User" >
insert into tb_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="userId != null" >
user_id,
</if>
<if test="userName !