配置typeAliasesPackage支援萬用字元包路徑掃描

木叔發表於2018-10-12

mybatis的xml檔案中需要寫類的全限定名,較繁瑣,可以配置自動掃描包路徑給類配置別名,兩種配置方式。

方式一:

mybatis-config.xml中配置

<typeAliases>
  <package name="com.xiaomu.context.config.model"/>
</typeAliases>

此配置不支援多路徑配置,不支援萬用字元配置,不靈活(個人實驗不行)

 

方式二:

SqlSessionFactory中配置typeAliasesPackage屬性

<bean id="mybatisSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="typeAliasesPackage" value="com.xiaomu.content.model,com.test.model"/>
    <property name="mapperLocations">
        <list>
            <value>classpath*:sql/**/*.xml</value>
        </list>
    </property>
</bean>

 

此種方式支援多路徑,逗號隔開,但是若有新路徑新增需要再次配置,不知情情況下容易疏漏,最好是萬用字元配置,目前不支援,可通過繼承重寫包路徑讀取方式來實現支援萬用字元配置
配置如下:

<bean id="mybatisSqlSessionFactory" class="com.xiaomu.jdbc.util.PackagesSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="typeAliasesPackage" value="com.xiaomu.**.model"/>
    <property name="mapperLocations">
        <list>
            <value>classpath*:sql/**/*.xml</value>
        </list>
    </property>
</bean>

 

java實現類程式碼:

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

public class PackagesSqlSessionFactoryBean extends SqlSessionFactoryBean {

    private static final Logger logger = LoggerFactory.getLogger(PackagesSqlSessionFactoryBean.class);
    
    static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
    
    @Override    
    public void setTypeAliasesPackage(String typeAliasesPackage) {    
        ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver();    
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);    
        typeAliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +    
                ClassUtils.convertClassNameToResourcePath(typeAliasesPackage) + "/" + DEFAULT_RESOURCE_PATTERN;    
    
        //將載入多個絕對匹配的所有Resource    
        //將首先通過ClassLoader.getResource("META-INF")載入非模式路徑部分    
        //然後進行遍歷模式匹配    
        try {
            List<String> result = new ArrayList<String>();
            Resource[] resources =  resolver.getResources(typeAliasesPackage);
            if(resources != null && resources.length > 0){
                MetadataReader metadataReader = null;
                for(Resource resource : resources){
                    if(resource.isReadable()){
                       metadataReader =  metadataReaderFactory.getMetadataReader(resource);
                        try {
                            result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());    
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            if(result.size() > 0) {
                super.setTypeAliasesPackage(StringUtils.join(result.toArray(), ","));
            }else{
                logger.warn("引數typeAliasesPackage:"+typeAliasesPackage+",未找到任何包");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }    
}

 

相關文章