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的值一定要是類的完全限定名)