Spring框架整合MyBatis框架

一、MyBatis和Spring整合过程

将 MyBatis 与 Spring 进行整合,主要解决的问题就是将 SqlSessionFactory 对象交由 Spring 来管理。所以,该整合,只需要将 SqlSessionFactory 的对象生成器 SqlSessionFactoryBean 注册在 Spring 容器中,再将其注入给 Dao 的实现类即可完成整合。实现 Spring 与 MyBatis 的整合常用的方式:扫描的 Mapper 动态代理 Spring 像插线板一样,mybatis 框架是插头,可以容易的组合到一起。插线板 spring 插上 mybatis,两个框架就是一个整体。
使用mybatis,需要创建mybatis框架中的某些对象,使用这些对象,就可以使用mybatis提供的功能了。

对于mybatis执行sql语句,需要用到的对象有:

  1. SqlSessionFactory对象,只有创建了SqlSessionFactory对象,才能调用openSession()方法得到SqlSession对象
  2. dao接口的代理对象,例如StudentDao接口,需要的代理对象为:SqlSeesion.getMapper(StudentDao.class)。
  3. 数据源DataSource对象,使用一个更强大、功能更多的连接池对象代替mybatis自己的PooledDataSource。

二、MyBatis和Spring整合实现的步骤

2.1 项目的大体框架

这里是spring整合mybatis之后,整个项目的架构图。

在这里插入图片描述

2.2 使用Navicat在数据库中创建一张表student

在这里插入图片描述

其中 id 字段为主键,同时设置了自动增长。

2.3 在pom.xml文件中加入maven依赖

<!-- spring依赖 -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.3.8</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>5.3.8</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>5.3.8</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-expression</artifactId>
  <version>5.3.8</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>5.3.8</version>
</dependency>
<!-- spring事务依赖 -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>5.3.8</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>5.3.8</version>
</dependency>
<!-- mybatis依赖 -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.16</version>
</dependency>
<!-- mybatis和spring集成依赖 -->
 <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.3</version>
 </dependency>
<!-- mysql驱动 -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
  <version>8.2.0</version>
</dependency>
<!-- 阿里的连接池 -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.12</version>
</dependency>
<!-- 单元测试 -->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13.2</version>
  <scope>test</scope>
</dependency>
<build>
    <resources>
      <resource>
        <directory>src/main/java</directory> <!--所在的目录-->
        <includes> <!--包括目录下的.properties,.xml 文件都会扫描到-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
</build>

2.4 编写实体类Student

package com.bjpowernode.entity;
 

public class Student {
 
    private Integer id;
    private String name;
    private Integer 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 Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
 
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2.5 编写StudentDao接口和对应的mapper映射文件

package com.bjpowernode.dao;
 
import com.bjpowernode.entity.Student;
 
import java.util.List;
 

public interface StudentDao {
 
    int insertStudent(Student student);
 
    List<Student> selectStudent();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.dao.StudentDao">
    <!-- 使用insert、update、delete、select标签编写sql语句 -->
    <insert id="insertStudent">
        insert into student2(name,age) values(#{name},#{age})
    </insert>
 
    <select id="selectStudent" resultType="com.bjpowernode.entity.Student">
        select id,name,age from student2
    </select>
 
</mapper>

2.6 编写MyBatis主配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE 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>
 
    <mappers>
<!--        <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>-->
        <!-- 将dao包下的所有mapper文件全部扫描 -->
        <package name="com.bjpowernode.dao"/>
    </mappers>
    
</configuration>

2.7 编写service接口和相应的实现类(目的是通过service调用dao接口中的方法)

package com.bjpowernode.service;
 
import com.bjpowernode.entity.Student;
 
import java.util.List;
 
/**
 *
 */
public interface StudentService {
 
    int addStudent(Student student);
 
    List<Student> queryStudent();
}
package com.bjpowernode.service.impl;
 
import com.bjpowernode.dao.StudentDao;
import com.bjpowernode.entity.Student;
import com.bjpowernode.service.StudentService;
 
import java.util.List;
 
public class StudentServiceImpl implements StudentService {
 
    private StudentDao studentDao;
 
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
 
    @Override
    public int addStudent(Student student) {
        int rows=studentDao.insertStudent(student);
        return rows;
    }
 
    @Override
    public List<Student> queryStudent() {
        List<Student> students=studentDao.selectStudent();
        return students;
    }
}

2.8 编写Spring配置文件

这里使用阿里的连接池、以及外部属性配置文件来读取数据库连接的相关信息。
先给出外部属性配置文件:jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&amp;characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
2.8.1 加载外部属性配置文件
<!-- 加载外部属性配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
2.8.2 声明数据源
<!-- 声明数据源DataSource -->
<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.password}"/>
</bean>
2.8.3 注册SqlSessionFactoryBean
<!-- 声明SqlSessionFactoryBean,在这个类的内部,创建SqlSessionFactory对象,之后就可以获取SqlSession对象 -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 指定数据源 -->
    <property name="dataSource" ref="myDataSource"/>
    <!-- 指定mybatis主配置文件 -->
    <property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
2.8.4 定义Mapper扫描配置器MapperScannerConfigurer
<!-- 声明MapperScannerConfigurer -->
<!--
     MapperScannerConfigurer作用:
       循环basePackage所表示的包,把包中的每个接口都找到,调用SqlSession.getMapper(XXXDao.class)
       把每个dao接口都创建出对应的dao代理对象,将dao代理对象放在容器中
       对于StudentDao接口,其代理对象为 studentDao
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 指定SqlSessionFactory对象的名称 -->
    <property name="sqlSessionFactoryBeanName" value="factory"/>
    <!-- 指定基本包,dao接口所在的包名 -->
    <property name="basePackage" value="com.bjpowernode.dao"/>
</bean>
2.8.5 向Service中注入相关的接口名
<!-- 声明service -->
<bean id="studentService" class="com.bjpowernode.service.impl.StudentServiceImpl">
    <property name="studentDao" ref="studentDao"/>
</bean>

2.9 编写测试方法

    @Test
    public void test01() {
        String config="applicationContext.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
 
        StudentDao studentDao= (StudentDao) ctx.getBean("studentDao");
 
        Student student=new Student();
        student.setName("李四");
        student.setAge(20);
        studentDao.insertStudent(student);
    }

在这里插入图片描述
在这里插入图片描述

总结

Spring整合MyBatis的总体步骤可以总结为以下几点:

spring集成mybatis,实现步骤:
1.使用mysql数据库,创建学生表student2(id int 自动增长,name varchar(30),age int)
2.创建maven项目
3.加入依赖
spring依赖、mybatis依赖、mysql驱动、junit单元测试
spring-mybatis依赖(mybatis网站上提供的,用来在spring项目中,创建mybatis对象)
spring有关事务的依赖
mybatis和spring整合的时候,事务是自动提交的。
4.创建实体类Student
5.创建dao接口和mapper文件,编写其中的sql语句
6.编写mybatis主配置文件
7.创建service接口和它的实现类
8.创建spring的配置文件

  1. 声明数据源DataSource,使用阿里的Druid连接池
  2. 声明SqlSessionFactoryBean类,在这个类的内部创建SqlSessionFactory对象
  3. 声明MapperScannerConfigurer类,在这个类的内部创建dao代理对象,创建的对象放在spring容器中
  4. 声明service对象,把3)中的dao赋值给service对象属性

9.测试dao访问数据库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值