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

由于数据库版本的不一样咱们须要写多个SQL,为了简化和提升维护性Mybatis提供了“_databaseId”内置参数来整合SQL以适应不一样版本数据库,Mybatis还提供了“_parameter”内置参数mysql

_databaseId:

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

<!-- 
		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配置,同时使用了这两个内置对象oracle

<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 &amp;&amp; custId!=null!=&quot;&quot;">
					其中&amp;是表明&符号;&quot;表明双引号
					
					为了阅读方便,推荐使用肺转移符
				-->
				<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并无写得很完整,只是为了说明两个内置参数的使用方式,不过仍是能够执行的。ide

相关文章
相关标签/搜索