<!-- mybatis文件配置,扫描所有mapper文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:/spring/mybatis.xml"/>
<property name="typeAliasesPackage" value="com.cloudwalk.shark.model"/>
<property name="mapperLocations" value="classpath*:mapper/*.xml"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<!--使用下面的方式配置参数,一行配置一个 -->
<value>
dialect=mysql
</value>
</property>
</bean>
</array>
</property>
</bean>
dataSource属性
该属性必须配置,多数据源时会有多个dataSource,同时也需要配置多个sqlSessionFactory来对应。
mapperLocations属性
配置该属性后,sqlSessionFactory会自动扫描该路径下的所有文件并解析。
该路径支持多个,可以用,;\t\n进行分割。
每一个路径都可以用直接的包路径,或者Ant风格的表达式。
configLocation属性
上面例子中并没有使用该属性,当SqlSessionFactoryBean提供的配置不能满足使用时,你可以使用mybatis-config.xml配置文件配置其他属性,然后通过configLocation属性指定该配置的路径,SqlSessionFactoryBean会使用该配置文件创建Configuration。
typeAliasesPackage属性
该属性可以给包中的类注册别名,注册后可以直接使用类名,而不用使用全限定的类名(就是不用包含包名)。
该属性可以配置多个,可以用,;\t\n进行分割。但是不支持Ant风格的路径。
plugins属性
该属性可以配置MyBatis的拦截器,拦截器的配置顺序会影响拦截器的执行顺序。
从上往下的拦截器,实际的执行顺序是这样,第一个拦截器会最后执行,最后一个会首先执行。
然后出拦截器的顺序和配置的顺序一致,第一个最先返回,最后一个最后返回。
就以上面的配置为例,一个简单的执行顺序图如下:
这些拦截器执行的顺序都是环绕型,不要简单理解为简单的顺序执行。
从配置顺序来看,第一个配置的在最里面,后面的依次环绕上一个拦截器。
MapperScannerConfigurer 配置
为了代替手工使用 SqlSessionDaoSupport 或 SqlSessionTemplate 编写数据访问对象 (DAO)的代码,MyBatis-Spring 提供了一个动态代理的实现:MapperFactoryBean。这个类 可以让你直接注入数据映射器接口到你的 service 层 bean 中。当使用映射器时,你仅仅如调 用你的 DAO 一样调用它们就可以了,但是你不需要编写任何 DAO 实现的代码,因为 MyBatis-Spring 将会为你创建代理。
示例
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.isea533.mybatis.mapper"/>
<property name="annotationClass" value="XXX"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
一般用过的最多也就是这3个属性,实际情况下最常用的只有basePackage。
basePackage属性
basePackage可以写多个,可以用,;\t\n进行分割。
每一个路径都可以用直接的包路径,或者Ant风格的表达式。
annotationClass属性
该属性实际上就是起到一个过滤的作用,如果设置了该属性,那么MyBatis的接口只有包含该注解,才会被扫描进去。
sqlSessionFactoryBeanName属性
这个属性一般都用不到,只有当你配置多数据源的时候,这是会有多个sqlSessionFactory,你就需要通过该属性来指定哪一个sqlSessionFactory(值为SqlSessionFactoryBean <bean>配置中的id属性)。
Ant通配符
? 匹配任何单字符
* 匹配0或者任意数量的字符
** 匹配0或者更多的目录
举例
/project/*.a 匹配项目根路径下所有在project路径下的.a文件
/project/p?ttern 匹配项目根路径下 /project/pattern 和 /app/pXttern,但是不包括/app/pttern
/**/example 匹配项目根路径下 /project/example, /project/foow/example, 和 /example
/project/**/dir/file.* 匹配项目根路径下/project/dir/file.jsp, /project/foow/dir/file.html
/**/*.jsp 匹配项目根路径下任何的.jsp 文件
最长匹配原则(has more characters)
URL请求/project/dir/file.jsp,现在存在两个路径匹配模式/**/*.jsp和/project/dir/*.jsp,那么会根据模式/project/dir/*.jsp来匹配
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
private Resource configLocation;
private Configuration configuration;
private Resource[] mapperLocations;
private DataSource dataSource;
private TransactionFactory transactionFactory;
private Properties configurationProperties;
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
private SqlSessionFactory sqlSessionFactory;
private String environment = SqlSessionFactoryBean.class.getSimpleName();
private boolean failFast;
private Interceptor[] plugins;
private TypeHandler<?>[] typeHandlers;
private String typeHandlersPackage;
private Class<?>[] typeAliases;
private String typeAliasesPackage;
private Class<?> typeAliasesSuperType;
private DatabaseIdProvider databaseIdProvider;
private Class<? extends VFS> vfs;
private Cache cache;
private ObjectFactory objectFactory;
private ObjectWrapperFactory objectWrapperFactory;
1、InitializingBean
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.dataSource, "Property ‘dataSource‘ is required");
Assert.notNull(this.sqlSessionFactoryBuilder, "Property ‘sqlSessionFactoryBuilder‘ is required");
Assert.state(this.configuration == null && this.configLocation == null || this.configuration == null || this.configLocation == null, "Property ‘configuration‘ and ‘configLocation‘ can not specified with together");
this.sqlSessionFactory = this.buildSqlSessionFactory();
}
// *****************************很重要,核心方法(自认为)*****************************************
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
XMLConfigBuilder xmlConfigBuilder = null;
Configuration targetConfiguration;
// 这里的targetConfiguration 就是配置文件中的 <property name="configLocation" value="classpath:/spring/mybatis.xml"/>具体是干嘛的后面再说
if (this.configuration != null) {
targetConfiguration = this.configuration;
if (targetConfiguration.getVariables() == null) {
targetConfiguration.setVariables(this.configurationProperties);
} else if (this.configurationProperties != null) {
targetConfiguration.getVariables().putAll(this.configurationProperties);
}
} else if (this.configLocation != null) {
xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), (String)null, this.configurationProperties);
targetConfiguration = xmlConfigBuilder.getConfiguration();
} else {
LOGGER.debug(() -> {
return "Property ‘configuration‘ or ‘configLocation‘ not specified, using default MyBatis Configuration";
});
targetConfiguration = new Configuration();
Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
}
Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
Optional.ofNullable(this.objectWrapperFactory).ifPresent(targetConfiguration::setObjectWrapperFactory);
Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);
String[] typeHandlersPackageArray;
if (StringUtils.hasLength(this.typeAliasesPackage)) {
typeHandlersPackageArray = StringUtils.tokenizeToStringArray(this.typeAliasesPackage, ",; \t\n");
Stream.of(typeHandlersPackageArray).forEach((packageToScan) -> {
targetConfiguration.getTypeAliasRegistry().registerAliases(packageToScan, this.typeAliasesSuperType == null ? Object.class : this.typeAliasesSuperType);
LOGGER.debug(() -> {
return "Scanned package: ‘" + packageToScan + "‘ for aliases";
});
});
}
if (!ObjectUtils.isEmpty(this.typeAliases)) {
Stream.of(this.typeAliases).forEach((typeAlias) -> {
targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);
LOGGER.debug(() -> {
return "Registered type alias: ‘" + typeAlias + "‘";
});
});
}
// 插件
if (!ObjectUtils.isEmpty(this.plugins)) {
Stream.of(this.plugins).forEach((plugin) -> {
targetConfiguration.addInterceptor(plugin);
LOGGER.debug(() -> {
return "Registered plugin: ‘" + plugin + "‘";
});
});
}
if (StringUtils.hasLength(this.typeHandlersPackage)) {
typeHandlersPackageArray = StringUtils.tokenizeToStringArray(this.typeHandlersPackage, ",; \t\n");
Stream.of(typeHandlersPackageArray).forEach((packageToScan) -> {
targetConfiguration.getTypeHandlerRegistry().register(packageToScan);
LOGGER.debug(() -> {
return "Scanned package: ‘" + packageToScan + "‘ for type handlers";
});
});
}
if (!ObjectUtils.isEmpty(this.typeHandlers)) {
Stream.of(this.typeHandlers).forEach((typeHandler) -> {
targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
LOGGER.debug(() -> {
return "Registered type handler: ‘" + typeHandler + "‘";
});
});
}
if (this.databaseIdProvider != null) {
try {
targetConfiguration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
} catch (SQLException var23) {
throw new NestedIOException("Failed getting a databaseId", var23);
}
}
Optional.ofNullable(this.cache).ifPresent(targetConfiguration::addCache);
if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
LOGGER.debug(() -> {
return "Parsed configuration file: ‘" + this.configLocation + "‘";
});
} catch (Exception var21) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocation, var21);
} finally {
ErrorContext.instance().reset();
}
}
targetConfiguration.setEnvironment(new Environment(this.environment, (TransactionFactory)(this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory), this.dataSource));
if (!ObjectUtils.isEmpty(this.mapperLocations)) {
Resource[] var24 = this.mapperLocations;
int var4 = var24.length;
for(int var5 = 0; var5 < var4; ++var5) {
Resource mapperLocation = var24[var5];
if (mapperLocation != null) {
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception var19) {
throw new NestedIOException("Failed to parse mapping resource: ‘" + mapperLocation + "‘", var19);
} finally {
ErrorContext.instance().reset();
}
LOGGER.debug(() -> {
return "Parsed mapper file: ‘" + mapperLocation + "‘";
});
}
}
} else {
LOGGER.debug(() -> {
return "Property ‘mapperLocations‘ was not specified or no matching resources found";
});
}
return this.sqlSessionFactoryBuilder.build(targetConfiguration);
}
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(Reader reader) {
return build(reader, null, null);
}
public SqlSessionFactory build(Reader reader, String environment) {
return build(reader, environment, null);
}
public SqlSessionFactory build(Reader reader, Properties properties) {
return build(reader, null, properties);
}
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(InputStream inputStream) {
return build(inputStream, null, null);
}
public SqlSessionFactory build(InputStream inputStream, String environment) {
return build(inputStream, environment, null);
}
public SqlSessionFactory build(InputStream inputStream, Properties properties) {
return build(inputStream, null, properties);
}
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
}
MyBatis源码(SqlSessionFactoryBuilder)
原文:https://www.cnblogs.com/longxok/p/10855691.html