您的位置:首页 > 数据库

Mybatis-动态SQL-内置参数_databaseId和_parameter

2018-01-30 00:00 567 查看
因为数据库版本的不同我们需要写多个SQL,为了简化和提高维护性Mybatis提供了“_databaseId”内置参数来整合SQL以适应不同版本数据库,Mybatis还提供了“_parameter”内置参数

_databaseId:

数据库版本,其值是在Mybatis全局配置文件中的<databaseIdProvider>标签中配置的

<!--
databaseIdProvider:支持多数据库厂商的;
type="DB_VENDOR":VendorDatabaseIdProvider是DB_VENDOR映射的实现类
作用:就是得到数据库厂商的标识,调用getDatabaseProductName()得到数据库名称,如Oracle(MySQL,SQL Server等其他名字)然后和配置中property比对,拿
到oracle,在与sql映射文件中<select>标签中的databaseid中的值匹配,Mybatis就能根据数据库厂商标识来执行不同的sql;
-->
<databaseIdProvider type="DB_VENDOR">
<property name="MySQL" value="mysql"/>
<property name="Oracle" value="oracle"/>
</databaseIdProvider>


_parameter:

由方法传递过来的参数,可以是任何参数类型,Java会把基本参数类型自动封装成包装类型

下面看一个SQL配置,同时使用了这两个内置对象

<select id="getCustsByCust" resultType="com.jv.dynamic.bean.Cust">
<if test="_parameter != null">
select cust_id,
<choose>
<when test="custId!=null and custId%2==0" >
concat(cust_name,'_aa') cust_name
</when>
<otherwise>
concat(cust_name,'_bb') cust_name
</otherwise>
</choose>
from cust
<where>
<!-- ognl表达式还支持&&等操作符,但是在xml中需要使用其转义字符
比如:<if test="custId!=null!=null && custId!=null!=""">
其中&是代表&符号;"代表双引号

为了阅读方便,推荐使用肺转移符
-->
<if test="custId!=null and custId!=''">
cust_id=#{custId}
</if>
<if test="custName!=null and custName!=''">
and cust_name like #{custName}
</if>
</where>
</if>
<if test="_parameter == null">
<!-- 因为是全表查询,需要限制返回的记录数,否则容易造成内存溢出 -->
select cust_id,cust_name from cust
<if test="_databaseId == 'mysql' ">
limit 1000
</if>
<if test="_databaseId == 'oracle'">
<![CDATA[
where rownum<1001
]]>
</if>
</if>
</select>

这个SQL并没有写得很完整,只是为了说明两个内置参数的使用方式,不过还是可以执行的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: