目錄
Mybatis typeAliasesPackage正規掃描
application.properties配置Mybatis 如下
Mybatis 自訂掃描通配符typeAliasesPackage
首頁 Java java教程 Springboot+Mybatis中怎麼實作typeAliasesPackage正規掃描

Springboot+Mybatis中怎麼實作typeAliasesPackage正規掃描

May 11, 2023 pm 12:19 PM
mybatis springboot typealiasespackage

Mybatis typeAliasesPackage正規掃描

mybatis預設配置typeAliasesPackage是不支援正規掃描package的,因此需要手動繼承org.mybatis.spring.SqlSessionFactoryBean,自己實作正規掃描,方法和傳統的spring mybatis區別,不同的是一個需要繼承類別一個是使用的掃描實作。

對於兩個或多個掃描路徑,範例:

cn.com.onethird.integration.entity

cn.com.onethird.business.entity

application.properties配置Mybatis 如下

mybatis.typeAliasesPackage=cn.com.onethird.*.*.entity
mybatis.mapperLocations=classpath:mapper/*.xml
登入後複製
package cn.com.onethird.nursinghome; 
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties; 
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
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;
import com.Application;
 
/** 
 * 
 * @Title: MyBatisConfig.java * 
 * @Package 
 * @Description: mybtis实现正则扫描java bean包 * 
 * @author 
 * @date 
 * @version V1.0 
 */
 
@Configuration
@PropertySource("classpath:application.properties")
public class MyBatisConfig {
    @Autowired
    private Environment env; 
    static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; 
    public static String 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;
        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) {
                HashSet<String> h = new HashSet<String>(result);
                result.clear();
                result.addAll(h);
                typeAliasesPackage = String.join("," ,(String[]) result.toArray(new String[0]));
            } else {
                throw new RuntimeException(
                        "mybatis typeAliasesPackage 路径扫描错误, 参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return typeAliasesPackage;
    }
 
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource)
            throws Exception {
        System.out.println(">>>>>>>>>>>配置[typeAliasesPackage,mapperLocations]START>>>>>>>>>>>>>>");
        Properties props = new Properties();
        String typeAliasesPackage = env
                .getProperty("mybatis.typeAliasesPackage");
        String mapperLocations = env.getProperty("mybatis.mapperLocations");
        typeAliasesPackage=setTypeAliasesPackage(typeAliasesPackage);
 
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        System.out.println(">>>>>>>>>>>配置[typeAliasesPackage,mapperLocations]END>>>>>>>>>>>>>>");
        return sessionFactory.getObject();
    }
 
    public static void main(String[] args) throws Exception {
        setTypeAliasesPackage("cn.com.onethird.*.*.entity");
    }
}
登入後複製

Mybatis 自訂掃描通配符typeAliasesPackage

typeAliasesPackage 預設只能掃描某一個路徑下,或以某一個路徑等分割的幾個路徑下的內容,不支援通配符和正規則,採用重寫的方式解決

package com.xxxx.xxx.util.common;    
import com.xxxx.xxx.util.LogUtil;  
import org.apache.commons.lang3.StringUtils;  
import org.mybatis.spring.SqlSessionFactoryBean;  
import org.slf4j.Logger;  
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;  
  
import java.io.IOException;  
import java.util.ArrayList;  
import java.util.List;  
  
/** 
 * Created by Administrator on 2015/10/6. 
 */  
public class PackagesSqlSessionFactoryBean extends SqlSessionFactoryBean {    
    static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";    
    private static Logger logger = LogUtil.get();    
    @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+",未找到任何包");  
            }  
            //logger.info("d");  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }    
}
登入後複製
<bean id="sqlSession" class="com.xxxx.xxxx.util.common.PackagesSqlSessionFactoryBean">  
        <property name="configLocation" value="classpath:config/sqlmap/sqlmap-config.xml" />  
        <property name="dataSource" ref="dataSource"/>  
        <!--<property name="mapperLocations"-->  
                  <!--value="classpath*:com/xxxx/xxxx/merchant/**/domain/mapper/*.xml"/>-->  
        <property name="typeAliasesPackage" value="com.xxxx.xxxx.custom.*.domain"/>  
        <property name="plugins">  
            <array>  
                <ref bean="pageInterceptor"/>  
            </array>  
        </property>  
    </bean>  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.xxxx.xxxx.**.dao"/>  
    </bean>
登入後複製

以上是Springboot+Mybatis中怎麼實作typeAliasesPackage正規掃描的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

iBatis和MyBatis:哪個比較適合你? iBatis和MyBatis:哪個比較適合你? Feb 19, 2024 pm 04:38 PM

iBatis和MyBatis:哪個比較適合你?

實作MyBatis中批次刪除操作的多種方式 實作MyBatis中批次刪除操作的多種方式 Feb 19, 2024 pm 07:31 PM

實作MyBatis中批次刪除操作的多種方式

詳解MyBatis動態SQL標籤中的Set標籤功能 詳解MyBatis動態SQL標籤中的Set標籤功能 Feb 26, 2024 pm 07:48 PM

詳解MyBatis動態SQL標籤中的Set標籤功能

比較分析JPA和MyBatis的功能和性能 比較分析JPA和MyBatis的功能和性能 Feb 19, 2024 pm 05:43 PM

比較分析JPA和MyBatis的功能和性能

MyBatis批次刪除語句的使用方法詳解 MyBatis批次刪除語句的使用方法詳解 Feb 20, 2024 am 08:31 AM

MyBatis批次刪除語句的使用方法詳解

MyBatis 一級快取詳解:如何提升資料存取效率? MyBatis 一級快取詳解:如何提升資料存取效率? Feb 23, 2024 pm 08:13 PM

MyBatis 一級快取詳解:如何提升資料存取效率?

MyBatis Generator配置參數解讀及最佳實踐 MyBatis Generator配置參數解讀及最佳實踐 Feb 23, 2024 am 09:51 AM

MyBatis Generator配置參數解讀及最佳實踐

解析MyBatis的快取機制:比較一級快取和二級快取的特性和用法 解析MyBatis的快取機制:比較一級快取和二級快取的特性和用法 Feb 25, 2024 pm 12:30 PM

解析MyBatis的快取機制:比較一級快取和二級快取的特性和用法

See all articles