最近的项目,最开始是使用MySQL进行开发,最终部署到多地区服务器。然而前几天说,有个地区的数据库使用的是Oracle。于是我要寻找一种方案,能让MySQL语法和Oracle语法同时存在。最终发现了MyBatis的这个神奇功能。
首先,配一个数据库配置:
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class DatabaseConfig {
/**
* 自动识别使用的数据库类型
* 在mapper.xml中databaseId的值就是跟这里对应,
* 如果没有databaseId选择则说明该sql适用所有数据库
* */
@Bean
public DatabaseIdProvider getDatabaseIdProvider(){
DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
Properties properties = new Properties();
properties.setProperty("Oracle","oracle");
properties.setProperty("MySQL","mysql");
properties.setProperty("DB2","db2");
properties.setProperty("Derby","derby");
properties.setProperty("H2","h2");
properties.setProperty("HSQL","hsql");
properties.setProperty("Informix","informix");
properties.setProperty("MS-SQL","ms-sql");
properties.setProperty("PostgreSQL","postgresql");
properties.setProperty("Sybase","sybase");
properties.setProperty("Hana","hana");
databaseIdProvider.setProperties(properties);
return databaseIdProvider;
}
}
然后就可以直接在mybatis文件中通过databaseId属性,来指定这个sql在什么数据库情况下执行:
<select id="listByName" parameterType="com.yuxx.pub.service.base.domain.vo.BaseAreaVo"
resultMap="com.yuxx.pub.service.base.biz.dao.BaseAreaMapper.BaseAreaResultMap" databaseId="mysql">
select
<include refid="BaseArea_Column_List_1"/>
from base_area a
<where>
<if test="areaName != null and areaName !=''">a.AREA_NAME like concat('%',#{areaName},'%') and</if>
a.area_id in(
SELECT area_id FROM(
SELECT
@ids as _ids,
( SELECT @ids := GROUP_CONCAT(area_id)
FROM base_area
WHERE FIND_IN_SET(parent_id, @ids)
) as cids,
@l := @l+1 as level
FROM base_area,
(SELECT @ids :=#{currUserAreaId}, @l := 0 ) b
WHERE @ids IS NOT NULL
) id, base_area DATA
WHERE FIND_IN_SET(DATA.area_id, ID._ids)
)
</where>
<if test="rowNum != null and rowNum !=''">
limit #{rowNum}
</if>
</select>
<select id="listByName" parameterType="com.yuxx.pub.service.base.domain.vo.BaseAreaVo"
resultMap="com.yuxx.pub.service.base.biz.dao.BaseAreaMapper.BaseAreaResultMap" databaseId="oracle" >
select
<include refid="BaseArea_Column_List_1"/>
from base_area a
<where>
<if test="areaName != null and areaName !=''">a.AREA_NAME like concat('%',#{areaName},'%') and</if>
a.area_id in(
select
area_id
from
base_area
start with
parent_id = #{currUserAreaId}
connect by prior
area_id = parent_id
)
</where>
<if test="rowNum != null and rowNum !=''">
limit #{rowNum}
</if>
</select>
就酱, 加上databaseId就可以指定要用的sql,mybatis会根据链接过来的DataSource自动识别。
来源:oschina
链接:https://my.oschina.net/alexjava/blog/4711124