目录
第四章、Spring集成MyBatis
4.1 介绍
利用ioc技术将spring和mybatis整合在一起。
为什么ioc能把spring和mybatis集成在一起,像一个框架一样使用?
因为ioc可以创建对象,可以把mybatis框架中的对象交给spring统一创建,开发人员从spring
中获取对象。这样开发人员就不用同时面对两个或多个框架了,就面对一个spring。
mybatis使用步骤:
1.定义dao接口,StudentDao
2.定义mapper文件StudentDao.xml
3.定义mybatis的主配置文件mybatis.xml
4.创建dao的代理对象,StudentDao dao = SqlSession.getMapper(StudentDao.class);
要使用dao对象,需要使用getMapper()方法,怎么能使用getMapper()方法,需要哪些条件?
1.获取SqlSession对象, 需要使用SqlSessionFactory的openSession()方法。
2.创建SqlSessionFactory对象。 通过读取mybatis的主配置文件,能创建SqlSessionFactory
对象。
3.需要SqlSessionFactory对象,使用Factory能获取SqlSession,有了SqlSession就能有
dao,目的就是获取dao对象。Factory创建需要读取主配置文件。
需要让spring创建以下对象:
1.独立的连接池类的对象, 使用阿里的druid连接池
2.SqlSessionFactory对象
3.创建出dao对象
4.2 整合步骤
1.新建maven项目
2.在maven的pom.xml文件中加入依赖:spring依赖、mybatis依赖、mysql依赖、spring的事务的依赖、mybatis和spring集成的依赖(mybatis官方提供的,用来在spring项目中创建mybatis的SqlSessionFactory、Dao对象的)
3.创建实体类
4.创建dao接口和对应的mapper文件
5.创建mybatis主配置文件
6.创建Service接口及其实现类,属性是对应的dao对象
7.创建spring的配置文件:声明mybatis的对象交给spring创建(数据源Datasource、SqlSessionFactory、Dao对象、Service对象)
8.创建测试类,获取service对象,通过service对象调用dao完成对数据库的访问操作
4.3 数据库准备
创建了数据库springdb,新建表Student。
4.4 maven依赖pom.xml文件
<dependencies>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--spring核心ioc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--做spring事务用到的-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--做spring事务用到的-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--mybatis依赖-->
<depen