Springboot+Mybatis中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>  

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • mybatis typeAliases 给实体类起别名的方法

    typeAliases 在我们开发中,Mapper中的实体类每次都要写上包名,是不是特别的麻烦 针对这一现象,myabtis提供了解决方案,简化开发 typeAliases标签 第一种用法 在主配置文件中 配置[不是映射文件,而是主配置文件] <typeAliases> <!--type:实体类的具体全限定类名, alias:别名--> <typeAlias type="com.yixuexi.entity.User" alias="User&q

  • MyBatis自定义typeHandler的完整实例

    自定义typeHandler 对于自定义typeHandler来说,需要在配置文件中注册typeHandlers 然后需要实现TypeHandler接口, 一个例子 首先编写调度的处理类 package com.ming.MyBatis; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeHandler; import org.apache.logging.log4j.LogManager; imp

  • 详解MyBatis配置typeAliases的方法

    0x00:前言参考 之前的<MyBatis 中 SqlMapConfig 配置文件详解>记了一下 MyBatis 中的核心配置文件各个标签的作用和使用场景,这篇文章细说一下配置文件中 typeAliases 标签的详细使用. 0x01:标签介绍 在 MyBatis 的 sql 映射配置文件中,需要使用 paramterType.resultType 来设置 sql 语句的输入输出参数,一般参数都是基本的数据类型或封装类型,但都需要声明该类型的全路径,java.lang.String,或者 cn

  • Mybatis中typeAliases的使用

    最近写接口的时候,关于返回值resultType="com.whiteme.po.User"之类的东西想来觉得有简化的方法,再看看一些代码发现果然有,于是写了这篇博客记录一下,这样的好处可能是以后包名换了比较好改(虽然可能性低),但是他解决了写全路径的问题,简化开发  typeAliases 单个定义 <typeAliases> <typeAlias alias="users" type="com.whiteme.po.Users&quo

  • Springboot+Mybatis中typeAliasesPackage正则扫描实现方式

    Mybatis typeAliasesPackage正则扫描 mybatis默认配置typeAliasesPackage是不支持正则扫描package的,因此需要手动继承org.mybatis.spring.SqlSessionFactoryBean,自己实现正则扫描,方法和传统的spring+mybatis没什么区别,不同的是一个需要继承类一个是使用的扫描实现. 对于两个或多个扫描路径,例: cn.com.onethird.integration.entity cn.com.onethird.

  • springboot实现指定mybatis中mapper文件扫描路径

    目录 指定mybatis中mapper文件扫描路径 mybatis配置多个扫描路径写法 指定mybatis中mapper文件扫描路径 所有的mapper映射文件 mybatis.mapper-locations=classpath*:com/springboot/mapper/*.xml 或者resource下的mapper映射文件 mybatis.mapper-locations=classpath*:mapper/**/*.xml mybatis配置多个扫描路径写法 百度得到,但是很乱,稍微

  • Mybatis中使用in()查询的方式详解

    目录 1 使用数组方式 2 使用List集合的方式 3 第三种我们使用Mybatis-plus框架的条件构造器来进行查询 附:Mybatis-plus的条件构造器详细使用教程 总结 这篇文章我会演示几种mybatis中使用in查询的方式. 1 数组.字符串 2 集合 3 使用Myabtis-plus框架的条件构造器来实现 我们在mysql中使用in查询的方式是这样的 那在mybatis中我们使用<foreach>标签来实现包含查询 1 使用数组方式 Mapper: Mapper.xml: &l

  • Mybatis中的Criteria条件查询方式

    Mybatis Criteria条件查询 Criterion Criterion是最基本,最底层的Where条件,用于字段级的筛选. Criteria Criteria包含一个Cretiron的集合,每一个Criteria对象内包含的Cretiron之间是由AND连接的,是逻辑与的关系. 其它 Example类的distinct字段用于指定DISTINCT查询. orderByClause字段用于指定ORDER BY条件,这个条件没有构造方法,直接通过传递字符串值指定. 代码示例 import

  • mybatis中foreach嵌套if标签方式

    目录 mybatis foreach嵌套if标签 xml文件 $和 #的区别 union与union all区别 mybatis if和foreach嵌套 (同一个列,不定个数的查询条件) 有这么一种需求 模板如下图 mybatis foreach嵌套if标签 代码实现: Mapper.java文件 List<Map<String, Object>> getYsxmcodeByYszbh(@Param("qyName") List<String> q

  • springboot整合mybatis中的问题及出现的一些问题小结

    1.springboot整合mybatis mapper注入时显示could not autowire,如果强行写(value  = false ),可能会报NullPointException异常 解决方案: dao层加注解@Component(value = "首字母小写的接口名如UserMapper->userMapper") dao层还可以加注解@Mapper 2.The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecogni

  • SpringBoot+Mybatis使用Mapper接口注册的几种方式

    目录 I. 环境准备 1. 数据库准备 2. 项目环境 II. 实例演示 1. 实体类,Mapper类 2. 注册方式 2.1 @MapperScan注册方式 2.2 @Mapper 注册方式 2.3 MapperScannerConfigurer注册方式 3. 小结 III. 不能错过的源码和相关知识点 SpringBoot项目中借助Mybatis来操作数据库,对大部分java技术栈的小伙伴来说,并不会陌生:我们知道,使用mybatis,一般会有下面几个 Entity: 数据库实体类 Mapp

  • springBoot mybatis 包扫描实例

    springBoot mybatis 包扫描 @MapperScan(basePackages = {"com.zscat.*.dao","com.zscat.*.*.dao"}) @EnableTransactionManagement(proxyTargetClass = true) @SpringBootApplication @MapperScan(basePackages = {"com.zscat.*.dao","com.z

  • Mybatis 中Mapper使用package方式配置报错的解决方案

    踩了个坑,写出来 Mybatis 中Mapper使用package方式配置报错 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) UserDaoTest中调用了UserDao的insert方法. 1.项目结构如下 2.UserDao接口 package com.mybatis.dao; import org.apache.ibatis.annotations.Mapper; import

  • SpringBoot中@Import注解的使用方式

    目录 一. @Import引入普通类 二. @Import引入配置类(@Configuration修饰的类) 三 .@Import引入ImportSelector的实现类 3.1 静态import场景(注入已知的类) 3.2 动态import场景(注入指定条件的类) 四. @Import引入ImportBeanDefinitionRegistrar的实现类 前言: @Import注解用来帮助我们把一些需要定义为Bean的类导入到IOC容器里面.下面我们就对@Import注解的使用做一个简单的总结

随机推荐