MyBatis标签与动态SQL
MyBatis通过 OGNL 来进行动态 SQL 的使用的。
对象导航图语言(Object Graph Navigation Language),简称OGNL,是应用于Java中的一个开源的表达式语言(Expression Language),它被集成在Struts2等框架中,作用是对数据进行访问,它拥有类型转换、访问对象方法、操作集合对象等功能。
既然说到mybatis中的动态sql,那就都总结一下吧。下面对mybaits标签进行分类:
一、定义sql语句
select 标签
属性介绍:
- id :唯一的标识符.
- parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User 或 user
- resultType :语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型,而不是集合本身(resultType 与 resultMap 不能并用)
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
select * from student where id=#{id}
</select>
insert 标签
与select用法相同
<insert id="insert" parameterType="com.admin.entity.Category">
insert into mall_category (id, parent_id, name,
status, sort_order, create_time,
update_time)
values (#{id,jdbcType=INTEGER}, #{parentId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR},
#{status,jdbcType=BIT}, #{sortOrder,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP},
#{updateTime,jdbcType=TIMESTAMP})
</insert>
delete标签
同上
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from mall_category
where id = #{id,jdbcType=INTEGER}
</delete>
update标签
同上
<update id="updateByPrimaryKey" parameterType="com.admin.entity.Category">
update mall_category
set parent_id = #{parentId,jdbcType=INTEGER},
name = #{name,jdbcType=VARCHAR},
status = #{status,jdbcType=BIT},
sort_order = #{sortOrder,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
二、定义结果集
resultMap 标签的使用
基本作用:
- 建立 SQL 查询结果字段与实体属性的映射关系信息
- 查询的结果集转换为 java 对象,方便进一步操作。
- 将结果集中的列与 java 对象中的属性对应起来并将值填充进去
!注意:与 java 对象对应的列不是数据库中表的列名,而是查询后结果集的列名
<resultMap id="BaseResultMap" type="com.admin.entity.Category">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="parent_id" jdbcType="INTEGER" property="parentId" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="status" jdbcType="BIT" property="status" />
<result column="sort_order" jdbcType="INTEGER" property="sortOrder" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
</resultMap>
标签说明:
主标签:
- id:该 resultMap 的标志
- type:返回值的类名,此例中返回 Studnet 类
子标签:
- id:用于设置主键字段与领域模型属性的映射关系,此处主键为 ID,对应 id。
- result:用于设置普通字段与领域模型属性的映射关系
属性说明:
- column:数据库的列名或者列标签别名。
- jdbcType:支持的JDBC类型列表中列出的JDBC类型。
- property:映射数据库列的字段或属性。
- javaType:完整java类名或别名
三、动态sql语句
动态 SQL 支持以下几种标签
元素 | 作用 | 备注 |
---|---|---|
if | 判断语句 | 单条件分支 |
choose(when otherwise) | 相当于if else | 多条件分支 |
where | 相当于where 1=1 | 用于处理SQL拼接问题 |
trim(where set) | 辅助元素 | 用于处理SQL拼接问题 |
foreach | 循环语句 | 批量插入更新查询时常用到 |
bind | 创建一个变量,并绑定上下文中 | 用于兼容不同的数据库,防止sql注入等 |
if 标签
if 标签是我们最常使用的。在查询、删除、更新的时候很可能会使用到。必须结合 test 属性联合使用。
if在where中使用
<select id="selectByStudentSelective" resultMap="BaseResultMap" parameterType="student">
select
<include refid="Base_Column_List" />
from student
where 1=1
<if test="name != null and name !=''">
and name like concat('%', #{name}, '%')
</if>
<if test="sex != null">
and sex=#{sex}
</if>
</select>
在此 SQL 语句中, where 1=1 是多条件拼接时的小技巧, 后面的条件查询就可以都用 and 了。
if在update中使用
<update id="updateByPrimaryKeySelective" parameterType="student">
update student
<set>
<if test="name != null">
`name` = #{name,jdbcType=VARCHAR},
</if>
<if test="phone != null">
phone = #{phone,jdbcType=VARCHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=TINYINT},
</if>
<if test="locked != null">
locked = #{locked,jdbcType=TINYINT},
</if>
<if test="gmtCreated != null">
gmt_created = #{gmtCreated,jdbcType=TIMESTAMP},
</if>
<if test="gmtModified != null">
gmt_modified = #{gmtModified,jdbcType=TIMESTAMP},
</if>
</set>
where student_id = #{studentId,jdbcType=INTEGER}
if在insert中使用
我们插入数据库中的一条记录, 不是每一个字段都有值的, 而是动态变化的。在这时候使用 if 标签, 可帮我们解决这个问题。只有非空属性才插入。
<insert id="insertSelective" parameterType="student">
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="studentId != null">
student_id,
</if>
<if test="name != null">
`name`,
</if>
<if test="phone != null">
phone,
</if>
<if test="email != null">
email,
</if>
<if test="sex != null">
sex,
</if>
<if test="gmtCreated != null">
gmt_created,
</if>
<if test="gmtModified != null">
gmt_modified,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="studentId != null">
#{studentId,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="phone != null">
#{phone,jdbcType=VARCHAR},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=TINYINT},
</if>
<if test="gmtCreated != null">
#{gmtCreated,jdbcType=TIMESTAMP},
</if>
<if test="gmtModified != null">
#{gmtModified,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
choose标签
choose when otherwise 标签可以帮我们实现 if else 的逻辑。一个 choose 标签至少有一个 when, 最多一个otherwise
<select id="selectByIdOrName" resultMap="BaseResultMap" parameterType="student">
select
<include refid="Base_Column_List" />
from student
where 1=1
<choose>
<when test="studentId != null">
and student_id=#{studentId}
</when>
<when test="name != null and name != ''">
and name=#{name}
</when>
<otherwise>
and 1=2
</otherwise>
</choose>
</select>
foreach标签
foreach 标签可以对数组, Map 或实现 Iterable 接口。
foreach 中有以下几个属性
- collection: 必填, 集合/数组/Map的名称.
- item: 变量名。即从迭代的对象中取出的每一个值
- index: 索引的属性名。当迭代的对象为 Map 时, 该值为 Map 中的 Key.
- open: 循环开头的字符串
- close: 循环结束的字符串
- separator: 每次循环的分隔符
接口方法中的参数如何设置
- 只有一个数组参数或集合参数
默认情况:集合collection=list, 数组是collection=array
推荐:使用 @Param 来指定参数的名称, 如我们在参数前@Param(“ids”), 则就填写 collection=ids - 多参数
多参数请使用 @Param 来指定, 否则SQL中会很不方便 - 参数是Map
指定为 Map 中的对应的 Key 即可。其实上面的 @Param 最后也是转化为 Map 的。 - 参数是对象
使用属性即可。
在where中使用foreach
<select id="selectByStudentIdList" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student
where student_id in
<foreach collection="list" item="id" open="(" close=")" separator="," index="i">
#{id}
</foreach>
</select>
foreach 实现批量插入
<insert id="insertList">
insert into student(name, phone, email, sex, locked)
values
<foreach collection="list" item="student" separator=",">
(
#{student.name}, #{student.phone},#{student.email},
#{student.sex},#{student.locked}
)
</foreach>
</insert>
bind 标签
创建一个变量,供上下文使用。
应用场景:在 MySQL 中, 该函数支持多参数, 但在 Oracle 中只支持两个参数。那么我们可以使用 bind 来让该 SQL 达到支持两个数据库的作用
<if test="name != null and name !=''">
<bind name="nameLike" value="'%'+name+'%'"/>
and name like #{nameLike}
</if>
四、格式化输出
辅助作用的标签,用来拼凑动态sql语句。
where标签
我们在写前面的[在 WHERE 条件中使用 if 标签] SQL 的时候, where 1=1 这个条件我们是不希望存在的。where标签就是解决不使用 where 1=1的问题。
<select id="selectByStudentSelectiveWhereTag" resultMap="BaseResultMap" parameterType="student">
select
<include refid="Base_Column_List" />
from student
<where>
<if test="name != null and name !=''">
and name like concat('%', #{name}, '%')
</if>
<if test="sex != null">
and sex=#{sex}
</if>
</where>
</select>
set标签
参考上面:if在update的使用
trim标签
set 和 where 其实都是 trim 标签的一种类型, 该两种功能都可以使用 trim 标签进行实现
trim 来表示 where
<trim prefix="where" prefixOverrides="AND |OR">
</trim>
表示当 trim 中含有内容时, 添加 where, 且第一个为 and 或 or 时, 会将其去掉。而如果没有内容, 则不添加 where。
trim来表示set
<trim prefix="SET" suffixOverrides=",">
</trim>
表示当 trim 中含有内容时, 添加 set, 且最后的内容为 , 时, 会将其去掉。而没有内容, 不添加 set
trim 的几个属性
- prefix: 当 trim 元素包含有内容时, 增加 prefix 所指定的前缀
- prefixOverrides: 当 trim 元素包含有内容时, 去除 prefixOverrides 指定的 前缀
- suffix: 当 trim 元素包含有内容时, 增加 suffix 所指定的后缀
- suffixOverrides:当 trim 元素包含有内容时, 去除 suffixOverrides 指定的后缀
五. 配置关联关系
collection 标签
association 标签
这两个标签单独来记录
六、定义变量及引用
sql 标签
当多种类型的查询语句的查询字段或者查询条件相同时,可以将其定义为常量,方便调用。为求 结构清晰也可将 sql 语句分解。
<!-- 查询字段 -->
<sql id="Base_Column_List">
ID,MAJOR,BIRTHDAY,AGE,NAME,HOBBY
</sql>
include 标签
用于引用定义的常量
<select id="selectAll" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM student
<include refid="Example_Where_Clause" />
</select>