其他动态标签
以下介绍两个标签,由于在实际开发中不经常使用,这里只介绍简单用法:
-
bind 标签的使用:
以模糊查询为例:当数据库为 MySQL 数据库时,模糊查询关键字为: concat(’%’,property,’%0’);具体代码如下:
MySQL 模糊查询
<if test = "userName != null and userName != ''">
and user_name like concat('%',#{userName},'%')
</if>
但是,当数据库被更换为 Oracle 以后,这个模糊查询的语法便会报错,因为 Oracle 数据库的 concat() 函数只有两个参数,如果要同时查询前后模糊,Oracle 的 concat() 函数的写法应该是:
Oracle 模糊查询
<if test = "userName != null and userName != ''">
and user_name like concat('%',concat(#{userName},'%'))
</if>
或者是这样的:
<if test = "userName != null and userName != ''">
and user_name like '%'||#{userName}||'%'
</if>
而 bind 标签可以定义一个变量名,将其绑定到动态上下文对象中,之后,在 XML 的 SQL 语句中,便可以使用这个变量名,针对上面这个 MySQL 数据库和 Oracle 数据库模糊查询的语法不通,可以通过使用 bind 标签来实现 SQL 语句兼容,示例如下:
<if test = "userName != null and userName != ''">
<bind name = "userNameLike" value = "'%' + userName + '%'" />
and user_name like #{userNameLike}
</if>
bind 标签的两个属性均为必填:
-
name : 上下文中设置的属性名
-
value : 为对原来的上下文属性做的处理
- databaseId 属性的使用
要使用 databaseId 属性,首先需要在 mybatis-config.xml 中配置,具体如下:
<databaseIdProvider type="DB_VENDOR">
<property name="SQL Server" value="sqlserver"/>
<property name="DB2" value="db2"/>
<property name="Oracle" value="oracle"/>
<property name="MySQL" value="mysql"/>
<property name="PostgreSQL" value="postgresql"/>
<property name="Derby" value="derby"/>
<property name="HSQL" value="hsqldb"/>
<property name="H2" value="h2"/>
</databaseIdProvider>
在这里 DB_VENDOR 的匹配策略为:DatabaseMetaData # getDatabaseProductName() 返回的字符串与 property 中的 name 部分的值做匹配,只要返回字符串包含 property 中的 name 部分,则匹配成功,databaseId 则会被设置为匹配成功后的 value 值;而这个 databaseId 在 MyBatis 解析参数时,会被放到一个 _databaseId 这个键对应的 value 值中。
DatabaseMetaData.class
// 由于我这里引入的是 MySQL 的 jar 包依赖,这个方法的返回值是 MySQL
@Override
public String getDatabaseProductName() throws SQLException {
return "MySQL";
}
在 XML 的 动态 SQL 编写中,我们便可使用 databaseId 属性了,支持 databaseId 属性的标签有:
- select
- insert
- update
- delete
- selectKey
- sql
这里仍然以模糊查询为例,使用 databaseId 的示例如下:
<select id = "selectByUser" databaseId = "mysql" resultMap = "SysUser" >
select * from sys_user where user_name like concat('%',#{userName},'%')
</select>
<select id = "selectByUser" databaseId = "oracle" resultMap = "SysUser" >
select * from sys_user where user_name like '%'||#{userName}||'%'
</select>
之后,MyBatis 便会根据数据库类型的不同,调用对应的 SQL 进行执行。
由于 databaseId 这个属性会在 MyBatis 解析参数的那一步被放到 _databaseId 对应的 value 值中,所以,上面的写法可以更简便,如下:
<select id = "selectByUser" resultMap = "SysUser" >
select * from sys_user where 1 = 1
<if test = "userName != null and userName != ''">
<if test = "_databaseId == 'mysql'">
and user_name like like concat('%',#{userName},'%')
</if>
<if test = "_databaseId == 'oracle'">
and user_name like like '%'||#{userName}||'%'
</if>
</if>
</select>