将 MyBatis 与 Spring 进行整合,主要解决的问题就是将 SqlSessionFactory 对象交由
Spring来管理。所以,该整合,只需要将 SqlSessionFactory 的对象生成器
SqlSessionFactoryBean 注册在 Spring 容器中,再将其注入给 Dao 的实现类即可完成整合。
实现 Spring 与 MyBatis 的整合常用的方式:扫描的 Mapper 动态代理。
Spring 像插线板一样,mybatis 框架是插头,可以容易的组合到一起。插线板 spring 插 上 mybatis,两个框架就是一个整体。
MySQL 创建数据库 springdb,新建表 Student
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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- mybatis的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!-- mybatis-spring两者集成的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mysql驱动-->
<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>
</dependencies>
<build>
<!-- 目的是将src/main/java目录中的xml文件包含到输出结果中。输出到classes目录中-->
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<!-- 指定jdk的版本-->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
定义实体类Student
public class Student{
private int id;
private String name;
private int age;
//set/get
}
定义StudentDao接口
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudents();
}
定义映射文件 mapper
在 Dao 接口的包中创建 MyBatis 的映射文件 mapper,命名与接口名相同,本例为StudentDao.xml。mapper 中的 namespace 取值也为 Dao 接口的全限定性名。
<?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.b204.dao.StudentDao">
<insert id="insertStudent">
insert into student values(#{id},#{name},#{email},#{age})
</insert>
<select id="selectStudents" resultType="com.b204.entity.Student">
select id,name,email,age from student order by id desc
</select>
</mapper>
定义 Service 接口和实现类
public interface StudentService {
int addStudent(Student student);
List<Student> queryStudents();
}
public class StudentServiceImpl implements StudentService {
//引用类型
private StudentDao studentDao;
//使用set注入,赋值
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public int addStudent(Student student) {
int res = studentDao.insertStudent(student);
return res;
}
@Override
public List<Student> queryStudents() {
List<Student> students = studentDao.selectStudents();
return students;
}
}
定义 MyBatis 主配置文件
在 src 下定义 MyBatis 的主配置文件,命名为 mybatis.xml。
(1)主配置文件中不再需要数据源的配置了。因为数据源要交给 Spring 容器来管理了。
(2)这里对 mapper 映射文件的注册,使用标签,即只需给出 mapper 映射文件所在的包即可。因为 mapper 的名称与 Dao 接口名相同,可以使用这种简单注册方式。这种方式的好处是,若有多个映射文件,这里的配置也是不用改变的。当然,也可使用原来的标签方式。
mybatis.xml
<?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>
<!--这里映射的是mapper.xml文件,如果有多个mapper文件,记得修改此处-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 设置别名-->
<typeAliases>
<!-- name:实体列的所在的包名-->
<package name="com.b204.entity"/>
</typeAliases>
<mappers>
<!-- name:是包名,这个包中的所有的mapper.xml一次都能加载-->
<package name="com.b204.dao"/>
</mappers>
</configuration>
从属性文件读取数据库连接信息
为了便于维护,可以将数据库连接信息写入到属性文件中,使 Spring 配置文件从中读取数据。属性文件名称自定义,但一般都是放在 src 下。
Spring 配置文件从属性文件中读取数据时,需要在的 value 属性中使用${ },
将在属性文件中定义的 key 括起来,以引用指定属性的值。
该属性文件若要被 Spring 配置文件读取,其必须在配置文件中进行注册。使用标签。
context:property-placeholder/方式
该方式要求在 Spring 配置文件头部加入 spring-context.xsd 约束文件
context:property-placeholder/标签中有一个属性 location,用于指定属性文件的位置。
<!-- 把数据库的配置信息,写在一个独立的文件,编译-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 使用属性配置文件中的数据,语法${key}-->
jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/springdb?characterEncoding=utf8
jdbc.username=root
jdbc.password=xxx
jdbc.maxActive=20
修改 Spring 配置文件
使用 JDBC 模板,首先需要配置好数据源,数据源直接以 Bean 的形式配置在 Spring 配置文件中。根据数据源的不同,其配置方式不同:
Druid 数据源 DruidDataSource
Druid 是阿里的开源数据库连接池。是 Java 语言中最好的数据库连接池。Druid 能
够提供强大的监控和扩展功能。Druid 与其他数据库连接池的最大区别是提供数据库的官网:https://github.com/alibaba/druid
applicationContext.xml
<?xml version="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">
<!-- 声明数据源DataSource,作用是连接数据库的配置内容
-->
<!-- 把数据库的配置信息,写在一个独立的文件,编译-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 使用属性配置文件中的数据,语法${key}-->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- set注入给DruidDataSource提供连接数据库信息-->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 最大连接数-->
<property name="maxActive" value="${jdbc.maxActive}"/>
</bean>
<!-- 声明的是mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- set注入,把数据库的连接池赋给了dataSource属性-->
<property name="dataSource" ref="myDataSource"/>
<!-- mybatis主配置文件的位置
configLocation属性是Resource类型,读取配置文件
它的赋值 使用value,指定文件的路径,使用classpath:表示文件的位置
-->
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!-- 创建dao对象,使用SqlSession的getMapper(StudentDao.class)
org.mybatis.spring.mapper.MapperScannerConfigurer在内部调用getMapper()生成每个dao接口的代理对象
Mapper 扫描配置器 MapperScannerConfigurer 会自动生成指定的基本包中 mapper 的代理对象。该 Bean 无需设置 id 属性。basePackage 使用分号或逗号设置多个包。
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定SQLSessionFactory对象的id-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 指定报名,报名是dao接口所在的包名
MapperScannerConfigure会扫描这个包中的所有接口,把每个接口都执行一次getMapper()
方法,得到每个接口的dao对象。创建好的dao对象放入spring的容器中。
dao对象的名称是接口名称的首字母小写
-->
<property name="basePackage" value="com.b204.dao"/>
</bean>
<!-- 声明service
向 Service 注入接口名
向 Service 注入 Mapper 代理对象时需要注意,由于通过 Mapper 扫描配置器
MapperScannerConfigurer 生成的 Mapper 代理对象没有名称,所以在向 Service 注入 Mapper代理时,无法通过名称注入。但可通过接口的简单类名注入,因为生成的是这个 Dao 接口
的对象。
-->
<bean id="studentService" class="com.b204.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"/>
</bean>
</beans>
测试文件:
public class MyTest {
@Test
public void test01(){
String config= "applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
String[] names = ac.getBeanDefinitionNames();
for (String name:names){
System.out.println("容器中对象的名称:"+name+"|||"+ac.getBean(name).getClass().getName());
}
}
@Test
public void test02(){
String config= "applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
//获取接口名首字母小写
StudentDao dao = (StudentDao)ac.getBean("studentDao");
Student student = new Student();
student.setId(1013);
student.setName("xxp");
student.setEmail("1883522888@qq.com");
student.setAge(24);
int res = dao.insertStudent(student);
System.out.println("nums="+res);
}
@Test
public void test03(){
String config= "applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
//获取接口名首字母小写
StudentService dao = (StudentService)ac.getBean("studentService");
Student student = new Student();
student.setId(1015);
student.setName("Curry");
student.setEmail("curry@qq.com");
student.setAge(30);
int res = dao.addStudent(student);
//spring 和 mybatis整合在一起使用,事务是自动提交的。无序执行sqlSession.commit()
System.out.println("nums="+res);
}
@Test
public void testServiceSelect(){
String config= "applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
StudentService dao = (StudentService)ac.getBean("studentService");
List<Student> students = dao.queryStudents();
for (Student student:students){
System.out.println(student);
}
}
}