Mybatis整合Spring -- typeAliasesPackage
Mybatis 整合 Spring
根据官方的说法,在 ibatis3,也就是 Mybatis3 问世之前,Spring3 的开发工作就已经完成了,所以 Spring3 中还是没有对 Mybatis3 的支持。因此由 Mybatis 社区自己开发了一个
Mybatis-Spring 用来满足 Mybatis 用户整合 Spring 的需求。下面就将通过 Mybatis-Spring 来整合 Mybatis 跟 Spring 的用法做一个简单的介绍。
MapperFactoryBean
首先,我们需要从 Mybatis 官网上下载 Mybatis-Spring 的 jar 包添加到我们项目的类路径下,当然也需要添加 Mybatis 的相关 jar 包和 Spring 的相关 jar 包。我们知道在 Mybatis 的所有
操作都是基于一个 SqlSession 的,而 SqlSession 是由 SqlSessionFactory 来产生的,SqlSessionFactory 又是由 SqlSessionFactoryBuilder 来生成的。但是 Mybatis-Spring 是基
于SqlSessionFactoryBean 的。在使用 Mybatis-Spring 的时候,我们也需要 SqlSession,而且这个 SqlSession 是内嵌在程序中的,一般不需要我们直接访问。SqlSession 也是
由SqlSessionFactory 来产生的,但是 Mybatis-Spring 给我们封装了一个 SqlSessionFactoryBean,在这个 bean 里面还是通过 SqlSessionFactoryBuilder 来建立对应的
SqlSessionFactory,进而获取到对应的 SqlSession。通过 SqlSessionFactoryBean 我们可以通过对其指定一些属性来提供 Mybatis 的一些配置信息。所以接下来我们需要在 Spring 的
applicationContext 配置文件中定义一个 SqlSessionFactoryBean。
@Configuration public class SessionFactoryConfiguration { @Value("${mapper_path}") private String mapperPath; //mybatis mapper 文件所在路径 @Value("${mybatis_config_file}") private String mybatisConfigFile; @Value("${entity_package}") private String entityPackage; @Autowired private DataSource dataSource; @Bean(name = "sqlSessionFactory") public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // 设置 mybatis configuration 扫描路径 sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFile)); // 添加 mapper 扫描路径 PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver(); String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath; sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath)); // 设置 dataSource sqlSessionFactoryBean.setDataSource(dataSource); // 设置 typeAlias 包扫描路径 sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage); return sqlSessionFactoryBean; } }
在定义 SqlSessionFactoryBean 的时候,dataSource 属性是必须指定的,它表示用于连接数据库的数据源。当然,我们也可以指定一些其他的属性,下面简单列举几个:
(1)mapperLocations:它表示我们的 Mapper 文件存放的位置,当我们的 Mapper 文件跟对应的 Mapper 接口处于同一位置的时候可以不用指定该属性的值。
(2)configLocation:用于指定 Mybatis 的配置文件位置。如果指定了该属性,那么会以该配置文件的内容作为配置信息构建对应的 SqlSessionFactoryBuilder,但是后续属性指定的内容会覆盖该配置文件里面指定的对应内容。
(3)typeAliasesPackage:它一般对应我们的实体类所在的包,这个时候会自动取对应包中不包括包名的简单类名作为包括包名的别名。多个 package 之间可以用逗号或者分号等来进行分隔。(value 的值一定要是包的全名)
(4)typeAliases:数组类型,用来指定别名的。指定了这个属性后,Mybatis 会把这个类型的短名称作为这个类型的别名,前提是该类上没有标注 @Alias 注解,否则将使用该注解对应的值作为此种类型的别名。(value 的值一定要是类的完全限定名)