业务场景:首先项目进行分布式拆分之后,按照模块再分为为api层和service层,web层。
其中订单业务的实体类放在com.muses.taoshop.item.entity,而用户相关的实体类放在com.muses.taoshop.user.entity。所以就这样,通过通配符方式去setTypeAliasesPackage ,com.muses.taoshop.*.entity
Ant通配符的3中风格:
(1) ?:匹配文件名中的一个字符 eg: com/test/entity? 匹配 com/test/entityaa
(2) * : 匹配文件名中的任意字符 eg: com/*/entity 匹配 com/test/entity
(3) ** : 匹配文件名中的多重路径 eg: com/**/entity 匹配 com/test/test1/entity
mybatis配置类写在common工程,数据库操作有些是可以共用的,不需要每个web工程都进行重复配置。
所以写了个Mybatis配置类:
贴一下配置类代码,主要关注: factoryBean.setTypeAliasesPackage(ENTITY_PACKAGES);之前的写法是这样的。ENTITY_PACKAGES是个常量:public static final String ENTITY_PACKAGES = "com.muses.taoshop.*.entity";,ps:注意了,这里用了通配符
package com.muses.taoshop.common.core.database.config; //省略jar进入代码 @MapperScan( basePackages = MAPPER_PACKAGES, annotationClass = MybatisRepository.class, sqlSessionFactoryRef = SQL_SESSION_FACTORY ) @EnableTransactionManagement @Configuration public class MybatisConfig { //省略其它代码,主要看sqlSessionFactory配置 @Primary @Bean(name = SQL_SESSION_FACTORY) public SqlSessionFactory sqlSessionFactory(@Qualifier(DATA_SOURCE_NAME)DataSource dataSource)throws Exception{ //SpringBoot默认使用DefaultVFS进行扫描,但是没有扫描到jar里的实体类 VFS.addImplClass(SpringBootVFS.class); SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); //factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml")); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try{ factoryBean.setMapperLocations(resolver.getResources("classpath*:/mybatis/*Mapper.xml")); //String typeAliasesPackage = packageScanner.getTypeAliasesPackages(); //设置一下TypeAliasesPackage factoryBean.setTypeAliasesPackage(ENTITY_PACKAGES); SqlSessionFactory sqlSessionFactory = factoryBean.getObject(); return sqlSessionFactory; }catch (Exception e){ e.printStackTrace(); throw new RuntimeException(); } } ... }ps:原先做法:在sqlSessionFactory方法里进行TypeAliasesPackage设置,(让Mybatis能够扫描到实体类,在xml文件里就不需要写全实体类的全包名了。)factoryBean.setTypeAliasesPackage(ENTITY_PACKAGES);
但是运行之后都会报错,提示实体类不能扫描到,因为我的service工程里都是这样写的,ResultType进行用别名ItemCategory,例子:
<!-- 获取所有的商品品类信息--> <select resultType="ItemCategory"> SELECT <include refid="BaseColumnList" /> FROM item_category t </select> 源码简单分析针对上面的业务场景,首先的分析一下,我们知道Mybatis的执行都会通过SQLSessionFactory去调用,调用前都是先用SqlSessionFactoryBean的setTypeAliasesPackage可以看一下SqlSessionFactoryBean的源码:
/** * Packages to search for type aliases. * * @since 1.0.1 * * @param typeAliasesPackage package to scan for domain objects * */ public void setTypeAliasesPackage(String typeAliasesPackage) { this我们看一下SqlSessionFactoryBean的初步Build方法:
/** * Build a {@code SqlSessionFactory} instance. * * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a * {@code SqlSessionFactory} instance based on an Reader. * Since 1.3.0, it can be specified a {@link Configuration} instance directly(without config file). * * @return SqlSessionFactory * @throws IOException if loading the config file failed */ protected SqlSessionFactory buildSqlSessionFactory() throws IOException { Configuration configuration; //创建一个XMLConfigBuilder读取配置文件的一些信息 XMLConfigBuilder xmlConfigBuilder = null; if (this.configuration != null) { configuration = this.configuration; if (configuration.getVariables() == null) { configuration.setVariables(this.configurationProperties); } else if (this.configurationProperties != null) { configuration.getVariables().putAll(this.configurationProperties);//添加Properties属性 } } else if (this.configLocation != null) { xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties); configuration = xmlConfigBuilder.getConfiguration(); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration"); } configuration = new Configuration(); if (this.configurationProperties != null) { configuration.setVariables(this.configurationProperties); } } if (this.objectFactory != null) { configuration.setObjectFactory(this.objectFactory); } if (this.objectWrapperFactory != null) { configuration.setObjectWrapperFactory(this.objectWrapperFactory); } if (this.vfs != null) { configuration.setVfsImpl(this.vfs); } /* 重点看这里,其它源码先不看,这里获取到typeAliasesPackage字符串之后,调用tokenizeToStringArray进行字符串分隔返回一个数组,`String CONFIG_LOCATION_DELIMITERS = ",; \t\n";` */ if (hasLength(this.typeAliasesPackage)) { String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeAliasPackageArray) {//遍历,注册到configuration对象上 configuration.getTypeAliasRegistry().registerAliases(packageToScan, typeAliasesSuperType == null ? Object.class : typeAliasesSuperType); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases"); } } } ... //省略其它代码 }