动态 SQL
通常写在mapper包下面的地址映射配置文件(.xml)中。根据条件的不同, SQL 语句也会随之动态的改变. MyBatis 中,提供了一组标签用于实现动态 SQL
动态SQL语句标签包括以下标签:
1、If标签
条件判断标签,通过判断参数取值来决定是否使用某个查询条件,基本用法如下:
<select id="queryBookIf" resultType="mybatis01.model.Book">
select <include refid="Base_Column_List"/>
from t_book where 1=1
<if test="null!=bookType and ''!=bookType">
<!--book_type 为数据库字段名-->
<!--bookType为实体类属性名-->
and book_type=#{bookType}
</if>
</select>
这里上面的sql语句后面必须添加 where 1=1 或者 使用where标签
if在这里是判断,判断书本类型是否为空 不为空就根据书本类型查询
id为mMapper的接口方法名,resultType为结果集类型
test 属性用于指定判断条件.
<include refid="Base_Column_List"/>为查询的所有字段
<sql id="Base_Column_List" >
book_id, book_name, book_name_pinyin, book_price, book_type
</sql>
2、trim标签:
trim标签用于控制sql语句的前缀及后缀,其具体属性如下:
属性 | 描述 |
prefix | 指定sql语句拼接的前缀 |
subfix | 指定sql语句拼接的后缀 |
prefixOverrides | 指定sql语句前面要去除的关键字或字符,如and 逗号 括号等 |
suffixOverrides | 指定sql语句后面要去除的关键字或字符 |
<insert id="insertSelective" parameterType="mybatis01.model.Book" >
insert into t_book
<!--prefix 在sql语句前拼一个(
insert into t_book (
-->
<!--suffix在sql语句后拼一个(
insert into t_book ()
-->
<!-- suffixOverrides 去除最后一个逗号
insert into t_book (book_id,book_name,)
取消这sql语句中最后一个逗号
-->
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="bookId != null" >
book_id,
</if>
<if test="bookName != null" >
book_name,
</if>
<if test="bookNamePinyin != null" >
book_name_pinyin,
</if>
<if test="bookPrice != null" >
book_price,
</if>
<if test="bookType != null" >
book_type,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="bookId != null" >
#{bookId,jdbcType=INTEGER},
</if>
<if test="bookName != null" >
#{bookName,jdbcType=VARCHAR},
</if>
<if test="bookNamePinyin != null" >
#{bookNamePinyin,jdbcTy