文章目录
前言
1.将 MyBatis 与 Spring 进行整合,主要解决的问题就是SqlSessionFactory 对象交由 Spring 来管理
2.该整合,只需要将SqlSessionFactory 的对象生成器SqlSessionFactoryBean 注册在 Spring 容器中,再将其注入给 Dao 的实现类即可完成整合
3.整合常用的方式:扫描的 Mapper 动态代理
一、项目结构
二、使用步骤
1.创建相应的数据库,数据表
2.向maven的pom.xm导入相应依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!--插件-->
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫
描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
3.定义bean包,并在其下定义相应实体类
4.定dao包,并在其下定义相应实体类Dao接口
4.在 dao包中创建 MyBatis 的映射文件 mapper
1.映射文件 mapper,命名与接口名相同
2.mapper 中的 namespace 取值为 Dao 接口的全类名
5.定义serivce包,并在其下定义Service接口及其实现类
6.定义 MyBatis 主配置文件
在 src 下定义 MyBatis 的主配置文件,命名为 mybatis.xml
7.修改 Spring 配置文件applicationContext.xml
(1) 数据源的配置
数据源配置两种方法。
1.直接输入配置信息。
2.从配置文件properties中读取
2.1在配置文件头部用<context:property-placeholder/>
中的属性 location,导入指定属性文件的位置
2.2在<property/>
的 value属性中使用${ },将在属性文件中定义的 key 括起来,以引用指定属性的值
(2) 注册 SqlSessionFactory的Bean
(3) 定义 Mapper 扫描配置器MapperScannerConfigurer
Mapper 扫描配置器 MapperScannerConfigurer 会自动生成指定的基本
包中 mapper 的代理对象。该 Bean 无需设置 id 属性。basePackage 使用芬号或逗号设置多个包。
(4) 向 Service 注入接口名
向 Service 注入 Mapper 代理对象时需要注意,由于通过 Mapper 扫描配
置器 MapperScannerConfigurer 生成的 Mapper 代理对象没有名称,所以在向 Service 注入 Mapper 代理时,无法通过名称注入。但可通过接口的简单类名注入,因为生成的是这个 Dao 接口的对象。