思维导图:
一.引言
这片文章建立在上篇文章的基础之上。在Spring集成了Spring MVC之后,我们需要利用Spring集成Mybates。这就是这片文章的功能。主要分为两个小节:
- Spring如何添加Mybatis配置
- 如何简单使用Mytatis
二.Spring集成Mybatis
在上一篇文章中我们介绍到,DispatherServlet的配置中有两个配置方法,即配置spring的视图解析器,控制器的webConfig的ServletConfig和配置数据库及其他中间件的RootConfig。显而易见,Mybatia就是配置在RootConfig上的。
我们可以在RootConfig上明确引入一个MybatisConfig的配置类以替代直接在RootConfig上配置Mybatis。如下:
/**
* ContextLoaderListner上下文的配置类
* 这个类的作用是配置数据层和中间件
* 比如,这次需要用spring集成mybatis,所以使用@Import注解引入了mybatis的配置类
*
* @author : zhouhao
* @date : Created in 2019/3/14 7:07
*/
@Configuration
@ComponentScan(excludeFilters={@ComponentScan.Filter(type= FilterType.ANNOTATION, value= EnableWebMvc.class)})
@Import(MybatisConfig.class)
public class MicroBlogRootConfig {
}
Spirng若想要集成Mybaits则需要配置两个必须的对象。其一是数据源,其二是Session工厂。如下:
/**
* Spring 集成 Mybatis的配置类
* 使用@PropertySource从配置文件中获取jdbc的配置属性
* 使用@MapperScan注解可以自动生成dao包下接口的实现类,而不用对每个DAO接口都使用@Mapper注解
*
* @author : zhouhao
* @date : Created in 2019/3/18 20:06
*/
@Confi