Mybatis动态SQL
动态sql
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
如果sql语句需要复用,可以将sql单写,方便复用
<sql id="if-title-author">
<if test="title != null">
title =#{title}
</if>
<if test="author != null">
and author =#{author}
</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select* from blog
<where>
<include refid="if-title-author"/>
</where>
</select>
choose when otherwise,类似于switch,case,default
<select id="queryBlogChoose" parameterType="blog" resultType="Blog">
select * from Blog
<where>
<choose>
<when test="title!=null">
title = #{title}
</when>
<when test="author!=null">
and author=#{author}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
set
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title !=null">
title =#{title},
</if>
<if test="author!=null">
author =#{author}
</if>
</set>
where id =#{id}
</update>
foreach
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="(" separator="or" close=")">
id = #{id}
</foreach>
</where>
</select>
模糊查询写法
<select id="selectUserByCond" parameterType="java.util.Map" resultType="user">
select
<include refid="BASE_COLUMNS"/>
from
<include refid="BASE_TABLE"/>
<where>
<if test="username!=null">
username=#{username}
</if>
<if test="lastLoginTime!=null">
and last_login like concat(#{lastLoginTime},'%')
</if>
</where>
</select>
UUID工具类
UUID是国际标准化组织(ISO)提出的一个概念。UUID是一个128比特的数值,这个数值可以通过一定的算法计算出来。为了提高效率,常用的UUID可缩短至16位。UUID用来识别属性类型,在所有空间和时间上被视为唯一的标识。一般来说,可以保证这个值是真正唯一的任何地方产生的任意一个UUID都不会有相同的值。
UUID是基于当前时间、计数器(counter)和硬件标识(通常为无线网卡的MAC地址)等数据计算生成的。UUID可以被任何人独立创建,并按需发布。UUID没有集中管理机构,因为它们是不会被复制的独特标识符。属性协议允许设备使用UUID识别属性类型,从而不需要用读/写请求来识别它们的本地句柄。
public class IDUtils {
public static String getID(){
return UUID.randomUUID().toString().replaceAll("-","");
}
@Test
public void test(){
System.out.println(IDUtils.getID());
}
}

浙公网安备 33010602011771号