---
title: "MyBatis常用的操作"
author: "tom_seed"
date: "2014-11-25T11:12:20Z"
tags: []
categories: ["企业架构"]
slug: "mybatis"
draft: false
lastmod: "2018-07-13T23:01:16Z"
id: 2160009
url: "https://tom-seed.iteye.com/blog/2160009"
---

**1.在&lt;where&gt;标签中为保证某一条件为true，且不影响其他判断条件**。最简单的解决方式：

```
<where>
  <if test="true">
	GMT_MODIFY = now()
  </if>
</where>
或者
<where>
  <if test="1==1">
	GMT_MODIFY = now()
  </if>
</where>
```

 

**2.Oracle、MySQL插入时返回主键的操作**

```
Oracle：
<insert id="insert" parameterClass="Cont">
	<selectKey keyProperty="id" resultClass="java.lang.Long" type="pre">
		SELECT SEQ_CONT.NEXTVAL AS ID FROM DUAL
    </selectKey>
	insert into CONT(ID, NAME, GMT_CREATE, GMT_MODIFY) values (#{id}, #{name}, sysdate, sysdate)
</insert>
注意：这边的keyProperty="id"中"id"指的是Java对象Cont中的属性，而并非数据库中CONT表的属性。
```

 

```
MySQL:
<insert id="insert" parameterType="Role" useGeneratedKeys="true" keyProperty="roleId">
    insert into role (name, create_time, update_time) values (#{name,jdbcType=VARCHAR}, now(), now())
</insert>
注意：role表的role_id字段是自动增长的，所以插入时不需要传入值；keyProperty="roleId"中"roleId"指的是Java对象Role中的属性，而并非数据库中role表的属性。
```

 

**3.插入、修改时存储创建、修改时间为数据库时间**

```
Oracle:
insert into CONT(ID, NAME, GMT_CREATE, GMT_MODIFY) values (#{id}, #{name}, sysdate, sysdate)

MySQL:
insert into role (name, create_time, update_time) values (#{name,jdbcType=VARCHAR}, now(), now())
```

 

**4.关系运算符的处理及转义**

主要处理的是小于/小于等于符号（”&lt;“/”&lt;=“）与XML的尖括号”&lt;“之间的冲突。可以用以下代码解决：

```
<where>
	<if test="id != null">
		<![CDATA[ AND T.ID < #{id} ]]>
	</if>
	...
</where>
包含在<![CDATA[      ]]>之间即可避免
```

 或者直接进行转义

```
<where>
	<if test="id != null"><!-- 大于号(>) -->
		AND T.ID &gt;= #{id, jdbcType=BIGINT}
	</if>
	<if test="id != null"><!-- 小于号(<) -->
		AND T.ID &lt;= #{id, jdbcType=BIGINT}
	</if>
	...
</where>
```

 常用转义字符如下：

显示结果

描述

实体名称

实体编号

 

空格

&nbsp;

&#160;

&lt;

小于号

&lt;

&#60;

&gt;

大于号

&gt;

&#62;

&

和号

&amp;

&#38;

"

引号

&quot;

&#34;

 

**5.批量插入、修改、删除操作**

```
<!-- MySQL批量插入 -->
<insert id="insertBatch" parameterType="java.util.List">
  insert into role_authority (role_id, authority_id) values
  <foreach collection="list" item="item" index="index" separator=",">
  	(${item.roleId}, ${item.authorityId})
  </foreach>
</insert>

<!-- MySQL、Oracle通过主键集合批量删除记录 -->
<delete id="batchRemove" parameterType="java.util.List">
  DELETE FROM ld_user WHERE id IN
  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
     #{item}
  </foreach>
</delete>

<!-- 批量修改与批量删除类似 -->
```

注意：SQL的执行长度有限制，需要注意不能超长

 

**6.模糊查询：**

```
<if test="entName != null and entName != ''">
	AND t2.`name` LIKE "%"#{entName,jdbcType=VARCHAR}"%"
	<!-- '%${entName,jdbcType=VARCHAR}%' -->
</if>
或者
<if test="voucherName != null">
	AND voucher_name = CONCAT('%',#{voucherName,jdbcType=VARCHAR},'%')
</if>
```