设为首页 收藏本站
查看: 539|回复: 0

[经验分享] Mybatis 分多个配置文, 重写org.mybatis.spring.SqlSessionFactoryBean支持多个mybatis-config.xml

[复制链接]

尚未签到

发表于 2016-11-25 08:28:09 | 显示全部楼层 |阅读模式
  现有版本的mybatis不支持多个mybatis-config.xml配置文件,但是实际应用中开发者希望它能与spring或struts一样支持多个配置文件,不同功能模块使用不同的配置文件以减少开发中代码检索的时间与维护成本.
  下面,是我根据网上资料结合自己实际遇到的问题重写的
  参考资料 http://www.xinglongjian.com/index.php/2012/09/15/mybatismanyconfig/
  上面的链接中只合并了 typeAliases与mappers
  但是我们实际的配置文件可能还包含 mybatis配置settings,mybatis插件plugins 至少我的项目需要这两项
  spring中配置

<bean id="sqlSessionFactory_db1" class="cn.com.softvan.dao.utils.MySqlSessionFactoryBean">
<property name="configLocationX" value="classpath*:config/mybatis/mybatis-config*.xml" />
<property name="dataSource" ref="dataSource_db1" />
</bean>

  具体类

package cn.com.softvan.dao.utils;
import static org.springframework.util.Assert.notNull;
import static org.springframework.util.ObjectUtils.isEmpty;
import static org.springframework.util.StringUtils.hasLength;
import static org.springframework.util.StringUtils.tokenizeToStringArray;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.sql.DataSource;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.TypeHandler;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.DocumentType;
import org.dom4j.Element;
import org.dom4j.ElementHandler;
import org.dom4j.ElementPath;
import org.dom4j.io.SAXReader;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.sun.beans.decoder.ValueObject;
public class MySqlSessionFactoryBean extendsorg.mybatis.spring.SqlSessionFactoryBean {
private static final Log logger = LogFactory.getLog(MySqlSessionFactoryBean.class);
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
private Interceptor[] plugins;
private Class<?>[] typeAliases;
private String typeAliasesPackage;
private TypeHandler<?>[] typeHandlers;
private String typeHandlersPackage;
private TransactionFactory transactionFactory;
private Properties configurationProperties;
private Resource[] configLocations;
private DataSource dataSource;
private String environment = SqlSessionFactoryBean.class.getSimpleName();
private DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
private Resource[] mapperLocations;
private SqlSessionFactory sqlSessionFactory;
//-settings 是否获取标记--防止多次获取--
private boolean settings_flag=true;
//-plugins 是否获取标记--防止多次获取--
private boolean plugins_flag=true;
/* 修改该方法 */
public void setConfigLocation(Resource configLocation) {
this.configLocations = configLocation != null ? new Resource[] { configLocation } : null;
}
/* 增加该方法 */
public void setConfigLocationX(String filePath) {
try {
ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver();  
//将加载多个模式匹配的Resource  
Resource[] resources = (Resource[]) resolver.getResources(filePath);  
configLocations=resources;
} catch (IOException e) {
e.printStackTrace();
}
if (logger.isDebugEnabled()) {
if(configLocations!=null){
for(Resource resource:configLocations){
logger.debug("==================================="+resource);
}
}
}
}
/**
* 合并mybatis配置文件
*/
public Document SQLConfigMap() {
Document doc = DocumentHelper.createDocument();
doc.setXMLEncoding("UTF-8");
DocumentFactory documentFactory = new DocumentFactory();
DocumentType docType = documentFactory.createDocType("configuration", "-//mybatis.org//DTD Config 3.0//EN", "http://mybatis.org/dtd/mybatis-3-config.dtd");
doc.setDocType(docType);
Element rootElement = doc.addElement("configuration");
rootElement.addElement("settings");
rootElement.addElement("typeAliases");
rootElement.addElement("plugins");
rootElement.addElement("mappers");
return doc;
}
public void readXML(Resource configXML,
final Element elementSettings,
final Element elementTypeAlias,
final Element elementPlugins,
final Element elementMapper) {
SAXReader saxReader = new SAXReader();
saxReader.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
String jarPath = SqlSessionFactory.class.getProtectionDomain()
.getCodeSource().getLocation().getPath();
String filePath = "org/apache/ibatis/builder/xml/mybatis-3-config.dtd";
InputStream jarIn = null;
try {
JarFile jarFile = new JarFile(jarPath);
JarEntry jarEntry = jarFile.getJarEntry(filePath);
jarIn = jarFile.getInputStream(jarEntry);
} catch (IOException e) {
e.printStackTrace();
}
return new InputSource(jarIn);
}
});
/* settings 获取*/
saxReader.addHandler("/configuration/settings/setting",
new ElementHandler() {
public void onEnd(ElementPath path) {
if(settings_flag){
//System.out.println("settings 获取---"+path.getPath());
Element row = path.getCurrent();
Element els = elementSettings.addElement("setting");
els.addAttribute("name", row.attributeValue("name"))
.addAttribute("value", row.attributeValue("value"));
row.detach();
}
}
public void onStart(ElementPath arg0) {
}
});
/* typeAliases合并 */
saxReader.addHandler("/configuration/typeAliases/typeAlias",
new ElementHandler() {
public void onEnd(ElementPath path) {
Element row = path.getCurrent();
Element els = elementTypeAlias.addElement("typeAlias");
els.addAttribute("alias", row.attributeValue("alias"))
.addAttribute("type",row.attributeValue("type"));
row.detach();
}
public void onStart(ElementPath arg0) {
}
});
/* plugins合并 */
saxReader.addHandler("/configuration/plugins/plugin",
new ElementHandler() {
public void onEnd(ElementPath path) {
if(plugins_flag){
//System.out.println("plugins 获取---"+path.getPath());
Element row = path.getCurrent();
Element els = elementPlugins.addElement("plugin");
els.addAttribute("interceptor", row.attributeValue("interceptor"));
//child
//System.out.println("xxxx=====xxx=="+row.elements().size());
if(row.elements()!=null){
Iterator iter=row.elementIterator();
while(iter.hasNext()){
Element oldels=(Element) iter.next();
Element els_property=els.addElement("property");
els_property.addAttribute("name", oldels.attributeValue("name"))
.addAttribute("value", oldels.attributeValue("value"));
}
}
row.detach();
}
}
public void onStart(ElementPath arg0) {
}
});
/* mapper合并 */
saxReader.addHandler("/configuration/mappers/mapper",
new ElementHandler() {
public void onEnd(ElementPath path) {
Element row = path.getCurrent();
Element els = elementMapper.addElement("mapper");
String mapper = row.attributeValue("mapper");
String resource = row.attributeValue("resource");
els.addAttribute("mapper", mapper);
els.addAttribute("resource", resource);
row.detach();
}
public void onStart(ElementPath arg0) {
}
});
try {
saxReader.read(configXML.getInputStream());
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @return SqlSessionFactory
* @throws IOException
*/
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Configuration configuration = null;
XMLConfigBuilder xmlConfigBuilder = null;
Document document = this.SQLConfigMap();
Element root = document.getRootElement();
Element elementSettings = root.element("settings");
Element elementTypeAlias = root.element("typeAliases");
Element elementPlugins = root.element("plugins");
Element elementMapper = root.element("mappers");
for (Resource configLocation : configLocations) {
readXML(configLocation,elementSettings, elementTypeAlias,elementPlugins, elementMapper);
settings_flag=false;
plugins_flag=false;
}
// Reader reader = null; InputStream inputStream = null;
if (this.configLocations != null) {
//--打印合并后的xml配置
logger.debug("xml="+document.asXML());
InputStream inputSteam = new ByteArrayInputStream(document.asXML().getBytes());
xmlConfigBuilder = new XMLConfigBuilder(inputSteam, null,
this.configurationProperties);
configuration = xmlConfigBuilder.getConfiguration();
if (inputSteam != null) {
inputSteam.close();
inputSteam = null;
}
document = null;
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'configLocation' not specified,using default MyBatis Configuration");
}
configuration = new Configuration();
configuration.setVariables(this.configurationProperties);
}
if (hasLength(this.typeAliasesPackage)) {
String[] typeAliasPackageArray = tokenizeToStringArray( this.typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packageToScan : typeAliasPackageArray) {
configuration.getTypeAliasRegistry().registerAliases(packageToScan);
if (logger.isDebugEnabled()) {
logger.debug("Scanned package: '" + packageToScan + "' for aliases");
}
}
}
if (!isEmpty(this.typeAliases)) {
for (Class<?> typeAlias : this.typeAliases) {
configuration.getTypeAliasRegistry().registerAlias(typeAlias);
if (logger.isDebugEnabled()) {
logger.debug("Registered type alias: '" + typeAlias + "'");
}
}
}
if (!isEmpty(this.plugins)) {
for (Interceptor plugin : this.plugins) {
configuration.addInterceptor(plugin);
if (logger.isDebugEnabled()) {
logger.debug("Registered plugin: '" + plugin + "'");
}
}
}
if (hasLength(this.typeHandlersPackage)) {
String[] typeHandlersPackageArray = tokenizeToStringArray( this.typeHandlersPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packageToScan : typeHandlersPackageArray) {
configuration.getTypeHandlerRegistry().register(packageToScan);
if (logger.isDebugEnabled()) {
logger.debug("Scanned package: '" + packageToScan + "' for type handlers");
}
}
}
if (!isEmpty(this.typeHandlers)) {
for (TypeHandler<?> typeHandler : this.typeHandlers) {
configuration.getTypeHandlerRegistry().register(typeHandler);
if (logger.isDebugEnabled()) {
logger.debug("Registered type handler: '" + typeHandler + "'");
}
}
}
if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
if (logger.isDebugEnabled()) {
logger.debug("Parsed configuration file: '" + this.configLocations + "'");
}
} catch (Exception ex) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocations, ex);
} finally {
ErrorContext.instance().reset();
}
}
if (this.transactionFactory == null) {
this.transactionFactory = new SpringManagedTransactionFactory();
}
Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (this.databaseIdProvider != null) {
try {
configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
} catch (SQLException e) {
throw new NestedIOException("Failed getting a databaseId", e);
}
}
if (!isEmpty(this.mapperLocations)) {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
mapperLocation.getInputStream(), configuration,
mapperLocation.toString(),
configuration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException(
"Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
ErrorContext.instance().reset();
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'mapperLocations' was not specified or no matching resources found");
}
}
return this.sqlSessionFactoryBuilder.build(configuration);
}
public void afterPropertiesSet() throws Exception {
notNull(dataSource, "Property 'dataSource' is required");
notNull(sqlSessionFactoryBuilder,"Property 'sqlSessionFactoryBuilder' is required");
this.sqlSessionFactory = buildSqlSessionFactory();
}
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
/*
* public Class<? extends SqlSessionFactory> getObjectType() { return
* this.sqlSessionFactory == null ? SqlSessionFactory.class :
* this.sqlSessionFactory.getClass(); }
*
* public void onApplicationEvent(ApplicationEvent event) { if (failFast &&
* event instanceof ContextRefreshedEvent) { // fail-fast -> check all
* statements are completed
* this.sqlSessionFactory.getConfiguration().getMappedStatementNames(); } }
*/
public SqlSessionFactoryBuilder getSqlSessionFactoryBuilder() {
return sqlSessionFactoryBuilder;
}
public void setSqlSessionFactoryBuilder(
SqlSessionFactoryBuilder sqlSessionFactoryBuilder) {
this.sqlSessionFactoryBuilder = sqlSessionFactoryBuilder;
}
public void setPlugins(Interceptor[] plugins) {
this.plugins = plugins;
}
public void setTypeAliases(Class<?>[] typeAliases) {
this.typeAliases = typeAliases;
}
public void setTypeAliasesPackage(String typeAliasesPackage) {
this.typeAliasesPackage = typeAliasesPackage;
}
public void setTypeHandlers(TypeHandler<?>[] typeHandlers) {
this.typeHandlers = typeHandlers;
}
public void setTypeHandlersPackage(String typeHandlersPackage) {
this.typeHandlersPackage = typeHandlersPackage;
}
public void setTransactionFactory(TransactionFactory transactionFactory) {
this.transactionFactory = transactionFactory;
}
public void setConfigurationProperties(Properties configurationProperties) {
this.configurationProperties = configurationProperties;
}
public void setMapperLocations(Resource[] mapperLocations) {
this.mapperLocations = mapperLocations;
}
public void setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
} else {
this.dataSource = dataSource;
}
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-305169-1-1.html 上篇帖子: MyBatis 单表CRUD 下篇帖子: Mybatis系列(七)关联映射
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表