Spring 集成 MyBatis
将 MyBatis 与 Spring 进行整合,主要解决的问题就是将 SqlSessionFactory 对象交由 Spring 来管理。所以,该整合,只需要将 SqlSessionFactory 的对象生成器SqlSessionFactoryBean 注 册在 Spring 容器中,再将其注入给 Dao 的实现类即可完成整合。
实现 Spring 与 MyBatis 的整合常用的方式:
扫描的 Mapper 动态代理 Spring 像插线板一样,mybatis 框架是插头,可以容易的组合到一起。插线板 spring 插 上 mybatis,两个框架就是一个整体。
1.这里我们还是使用的是SSM数据库中的student表

2. maven 依赖 pom.xml
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>4.11version>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-contextartifactId>
- <version>5.2.5.RELEASEversion>
- dependency>
- <dependency
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-txartifactId>
- <version>5.2.5.RELEASEversion>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-jdbcartifactId>
- <version>5.2.5.RELEASEversion>
- dependency>
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatisartifactId>
- <version>3.5.1version>
- dependency>
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatis-springartifactId>
- <version>1.3.1version>
- dependency>
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>5.1.9version>
- dependency>
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>druidartifactId>
- <version>1.1.12version>
- dependency>
-
- <build>
- <resources>
- <resource>
- <directory>src/main/javadirectory>
- <includes>
- <include>**/*.propertiesinclude>
- <include>**/*.xmlinclude>
- includes>
- <filtering>falsefiltering>
- resource>
- resources>
- <plugins>
- <plugin>
- <artifactId>maven-compiler-pluginartifactId>
- <version>3.1version>
- <configuration>
- <source>1.8source>
- <target>1.8target>
- configuration>
- plugin>
- plugins>
- build>
项目结构:

3. 定义实体类 Student
- package com.bjpowernode.domain;
-
- public class Student {
- //属性名和列名一样。
- private Integer id;
- private String name;
- private String email;
- private Integer age;
-
- public Student() {
- }
-
- public Student(Integer id, String name, String email, Integer age) {
- this.id = id;
- this.name = name;
- this.email = email;
- this.age = age;
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getEmail() {
- return email;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
-
- public Integer getAge() {
- return age;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
-
- @Override
- public String toString() {
- return "Student{" +
- "id=" + id +
- ", name='" + name + '\'' +
- ", email='" + email + '\'' +
- ", age=" + age +
- '}';
- }
- }
4.定义 StudentDao 接口
- package com.bjpowernode.dao;
-
- import com.bjpowernode.domain.Student;
-
- import java.util.List;
-
- public interface StudentDao {
-
- int insertStudent(Student student);
-
- List
selectStudents(); -
- }
5定义映射文件 mapper
在 Dao 接口的包中创建 MyBatis 的映射文件 mapper,命名与接口名相同,本例为 StudentDao.xml。mapper 中的 namespace 取值也为 Dao 接口的全限定性名。
- "1.0" encoding="UTF-8" ?>
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.bjpowernode.dao.StudentDao">
-
- <insert id="insertStudent">
- insert into student values(#{id},#{name},#{email},#{age})
- insert>
-
- <select id="selectStudents" resultType="Student">
- select id,name,email,age from student order by id desc
- select>
- mapper>
6定义 Service 接口和实现类
- //接口
- package com.bjpowernode.service;
-
- import com.bjpowernode.domain.Student;
-
- import java.util.List;
-
- public interface StudentService {
-
- int addStudent(Student student);
- List
queryStudents(); - }
-
- //实现类
- package com.bjpowernode.service.impl;
-
- import com.bjpowernode.dao.StudentDao;
- import com.bjpowernode.domain.Student;
- import com.bjpowernode.service.StudentService;
-
- import java.util.List;
-
- public class StudentServiceImpl implements StudentService {
-
- //引用类型
- private StudentDao studentDao;
-
- //使用set注入,赋值
- public void setStudentDao(StudentDao studentDao) {
- this.studentDao = studentDao;
- }
-
- @Override
- public int addStudent(Student student) {
- int nums = studentDao.insertStudent(student);
- return nums;
- }
-
- @Override
- public List
queryStudents() { - List
students = studentDao.selectStudents(); - return students;
- }
- }
7定义 MyBatis 主配置文件
在 src 下定义 MyBatis 的主配置文件,命名为 mybatis.xml。 这里有两点需要注意:
(1)主配置文件中不再需要数据源的配置了。因为数据源要交给 Spring 容器来管理了。
(2)这里对 mapper 映射文件的注册,使用标签,即只需给出 mapper 映射文件 所在的包即可。因为 mapper 的名称与 Dao 接口名相同,可以使用这种简单注册方式。这种 方式的好处是,若有多个映射文件,这里的配置也是不用改变的。当然,也可使用原来的 标签方式。
- "1.0" encoding="UTF-8" ?>
- configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
-
-
- <settings>
-
- <setting name="logImpl" value="STDOUT_LOGGING"/>
- settings>
-
-
- <typeAliases>
-
- <package name="com.bjpowernode.domain"/>
- typeAliases>
-
-
-
- <mappers>
-
- <package name="com.bjpowernode.dao"/>
- mappers>
- configuration>
8Spring 配置文件(重点)
使用 JDBC 模板,首先需要配置好数据源,数据源直接以 Bean 的形式配置在 Spring 配 置文件中。根据数据源的不同,其配置方式不同:
Druid 数据源 DruidDataSource
Druid是阿里的开源数据库连接池。是 Java 语言中最好的数据库连接池。Druid 能 够提供强大的监控和扩展功能。Druid 与其他数据库连接池的最大区别是提供数据库的
官网:https://github.com/alibaba/druid 使用地址:https://github.com/alibaba/druid/wiki/常见问题
- 据源的配置(掌握)

-
从属性文件读取数据库连接信息

-
注册 SqlSessionFactoryBean

-
定义 Mapper 扫描配置器 MapperScannerConfigurer
Mapper 扫描配置器 MapperScannerConfigurer 会自动生成指定的基本包中 mapper 的代 理对象。该 Bean 无需设置 id 属性。basePackage 使用分号或逗号设置多个包。

-
向 Service 注入接口名
向 Service 注入 Mapper 代理对象时需要注意,由于通过 Mapper 扫描配置器 MapperScannerConfigurer 生成的 Mapper 代理对象没有名称,所以在向 Service 注入 Mapper 代理时,无法通过名称注入。但可通过接口的简单类名注入,因为生成的是这个 Dao 接口 的对象。

9 全局的配置文件如下:
- "1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
-
-
- <context:property-placeholder location="classpath:jdbc.properties" />
-
-
- <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
- init-method="init" destroy-method="close">
-
-
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}"/>
- <property name="password" value="${jdbc.passwd}" />
- <property name="maxActive" value="${jdbc.max}" />
- bean>
-
-
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
-
- <property name="dataSource" ref="myDataSource" />
-
- <property name="configLocation" value="classpath:mybatis.xml" />
- bean>
-
-
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
-
- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
-
- <property name="basePackage" value="com.bjpowernode.dao"/>
- bean>
-
-
- <bean id="studentService" class="com.bjpowernode.service.impl.StudentServiceImpl">
- <property name="studentDao" ref="studentDao" />
- bean>
-
- beans>
10,测试
- package com.bjpowernode;
-
- import com.bjpowernode.dao.StudentDao;
- import com.bjpowernode.domain.Student;
- import com.bjpowernode.service.StudentService;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- import java.util.List;
-
- public class MyTest {
-
- @Test
- public void test01(){
-
- String config="applicationContext.xml";
- ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
- String names[] = ctx.getBeanDefinitionNames();
- for(String na:names){
- System.out.println("容器中对象名称:"+na+"|"+ctx.getBean(na));
- }
- }
-
- @Test
- public void testDaoInsert(){
-
- String config="applicationContext.xml";
- ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
- //获取spring容器中的dao对象
- StudentDao dao = (StudentDao) ctx.getBean("studentDao");
- Student student = new Student();
- student.setId(1013);
- student.setName("zhoufeng");
- student.setEmail("zhoufeng@qq.com");
- student.setAge(20);
- int nums = dao.insertStudent(student);
- System.out.println("nums="+nums);
- }
-
- @Test
- public void testServiceInsert(){
-
- String config="applicationContext.xml";
- ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
- //获取spring容器中的dao对象
- StudentService service = (StudentService) ctx.getBean("studentService");
- Student student = new Student();
- student.setId(1015);
- student.setName("lishengli");
- student.setEmail("zhoufeng@qq.com");
- student.setAge(26);
- int nums = service.addStudent(student);
- //spring和mybatis整合在一起使用,事务是自动提交的。 无需执行SqlSession.commit();
- System.out.println("nums="+nums);
- }
-
- @Test
- public void testServiceSelect(){
-
- String config="applicationContext.xml";
- ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
- //获取spring容器中的dao对象
- StudentService service = (StudentService) ctx.getBean("studentService");
-
- List
students = service.queryStudents(); - for (Student stu:students){
- System.out.println(stu);
- }
- }
- }
