动态sql
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦
if
<select id="selectBy1" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from product where 1=1
<if test="id !=null and id !=''">
and id = #{id,jdbcType=NUMERIC}
</if>
<if test="name !=null and name !=''">
and name = #{name,jdbcType=VARCHAR}
</if>
</select>
标签 | 含有 |
---|---|
if test=’‘ | 条件 |
Where
<select id="selectBy1" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from product <where>
<if test="id !=null and id !=''">
and id = #{id,jdbcType=NUMERIC}
</if>
<if test="name !=null and name !=''">
and name = #{name,jdbcType=VARCHAR}
</if>
</where>
</select>
能将第一个匹配条件的内容前的and或者or去掉
trim
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
标签值 | 含有 |
---|---|
prefix | trim前面添加指定内容 |
prefixOverrides | trim前面删除指定内容 |
suffix | trim后面添加指定内容 |
suffixOverrides | trim后面添加删除内容 |
能将第一个匹配条件的内容前的and或者or去掉 |
choose、when、otherwise
相当于ifeles。。。ifelse
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
表示if else 。。 ifelse 只有一个匹配一个,下面就不匹配
forerch
<if test="depIds.size()>0 and depIds !=null">
and mptd.team_dep_id in(
<foreach collection="depIds" separator="," item="depId">
#{depId,jdbcType=BIGINT}
</foreach>
)
</if>
标签值 | 含义 |
---|---|
collection | 当前入参迭代器 |
item | 集合项 |
index | 索引 |
open | 以…开头 |
close | 以…结束 |
separator | 分隔符 |
SQL
SQL标签就是sql字段
<!--定义-->
<sql id="Base_Column_List">
id,name,price,
version
</sql>
<!--使用-->
<select id="select" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from product
</select>
缓存机制
缓存是存在于内存中的临时数据,使用缓存减少和数据库的交互次数,提高执行效率。
一级缓存
默认开启,范围级别sqlSerssion,一级缓存无过期时间,只有生命周期
二级缓存
手动开启,范围级别sqlSerssionFactory,一级缓存无过期时间,只有生命周期。默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。 要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:
<cache/>
开启:设置全局配置属性加标签,在sqlSerssion关闭或者提交,实体类序列化