Spring整合Mybatis详解
技术点
1、使用的技术是IOC
2、为什么使用IOC:能够把mybatis和spring集成在一起,是因为IOC能够创建对象。可以把mybatis框架中的对象交给spring统一管理。开发人员就能从spring中获取对象。
Mybatis使用步骤:
1、定义dao接口,StudentDao
2、定义mapper.xml文件,StudenDao.xml
3、定义mybatis主配置文件,mybatis.xml
4、创建dao的代理对象StudentDao dao = SqlSession.getMapper(StudentDao.class); List<Student> students = dao.selectStudens();
要使用dao对象,需要使用getMapper()方法,怎么能使用getMapper()方法,需要哪些条件?(考点)
1、获取SqlSession对象,需要使用SqlSessionFactory的openSession()方法。
2、创建SqlSessionFactory对象。通过读取mybatis的主配置文件,能够创建SqlSessionFactory对象。需要SqlSessionFactory对象,使用Factory能获取SqlSession,有了SqlSession就能有dao,目的是获取dao对象,Factory创建需要读取mybatis主配置文件。
Mybatis主配置
参考mybatis官方文档进行配置
>>> https://mybatis.org/mybatis-3/zh/index.html <<<
主要两点
(1)数据库信息配置(数据源):当在大型项目中mybatis自带的连接池相对较弱,一般使用阿里云的druid连接池
(2)mapper映射文件的配置
总结:spring 需要创建以下对象(考点)
1、独立连接池类的对象,使用阿里云的druid连接池(数据库驱动对象)
2、SqlSessionFactory对象
3、创建dao对象(持久层)
spring与Mybatis整合步骤
1、新建maven项目
2、加入maven依赖
(1)spring依赖
(2)mybatis依赖
(3)MySQL驱动
(4)spring的事务依赖
(5)spring和mybatis集成的依赖:mybatis官方用的,用在spring项目中创建mybatis的SqlSessionFactory,dao对象的
(6)日志依赖等等… …
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.spring</groupId>
<artifactId>ch07-spring-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<name>ch07-spring-mybatis</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.3.3</spring.version>
</properties>
<dependencies>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring做事务的-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!--lo4j-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<!--resource的目的是把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>
</build>
</project>
3、创建实体类
package com.spring.entity;
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、创建dao接口和mapper文件
(1)dao接口
package com.spring.dao;
import com.spring.entity.Student;
import java.util.List;
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudent();
}
(2)mapper文件(xml文件)
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.spring.dao.StudentDao">
<resultMap id="BaseStudentMap" type="com.spring.entity.Student"/>
<sql id="sql_column">
id,name,email,age
</sql>
<!--添加-->
<insert id="insertStudent" parameterType="com.spring.entity.Student">
insert into student(name,email,age)
values(#{name},#{email},#{age})
</insert>
<!--查询-->
<select id="selectStudent" resultMap="BaseStudentMap">
select <include refid="sql_column"/>
from student
order by id asc
</select>
</mapper>
5、创建mybatis主配置文件(日志参考mybatis的整log4j
)
<?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>
<!--setting:控制mybatis全局行为-->
<settings>
<!--设置mybatis输出日志-->
<setting name="logImpl" value="LOG4J"/>
</settings>
<!--设置别名-->
<typeAliases>
<!--name:实体类所在的包名-->
<package name="com.spring.entity"/>
</typeAliases>
<!--mapper:sql映射文件的位置-->
<mappers>
<!--name:如果是package,这个包中所有的mapper一次性导入
如果是mapper,表示的是指定导入mapper
-->
<package name="com.spring.dao"/>
<!-- <mapper resource="com/spring/dao/StudentDao.xml"/>-->
</mappers>
</configuration>
6、创建service接口和实现类,属性是dao
(1)service接口
package com.spring.service;
import com.spring.entity.Student;
import java.util.List;
public interface StudentService {
/*添加*/
int addStudent(Student student);
/*查询*/
List<Student> queryStudents();
}
(2)service接口实现类
package com.spring.service;
import com.spring.dao.StudentDao;
import com.spring.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
//引用类型
// @Resource
// @Autowired
private StudentDao studentDao;
/**
* 如果不使用注解,可以使用设置注入
*/
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public int addStudent(Student student) {
return studentDao.insertStudent(student);
}
@Override
public List<Student> queryStudents() {
return studentDao.selectStudent();
}
}
7、创建spring的配置文件:声明mybatis的对象交给spring创建
(1)数据源
(2)SqlSessionFactory
(3)dao对象
jdbc.properties数据库相关配置
jdbc.url = jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = 123456
# 最大连接数
maxActive = 20
<?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">
<!--引入properties属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--使用阿里云的druid连接池-->
<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}"/>
<property name="maxActive" value="${maxActive}"/>
</bean>
<!--
<context:component-scan base-package="com.spring"/>
-->
<!--
声明的是mybatis中提供的SqlSessionFactoryBean类,
这个类内部创建SqlSessionFactory的
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<!--mybatis主配置文件的位置
configLocation的属性是Resource类型,读取外部的配置文件的
它的赋值,使用value,指定配置文件的路径,使用classpath:配置文件
-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--创建dao对象,使用SqlSession.getMapper(Student.class)
MapperScannerConfigurer:在内部调用getMapper()生成每个dao接口的代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定SqlSessionFactory对象的id-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--指定包名,包名是dao接口所在的包名
MapperScannerConfigurer会扫描这个包中的所有接口,包每个接口都执行一次getMapper()方法,得到每个接口的dao对象
创建好的dao对象放入到spring容器中。dao对象的名称是接口名字首字母小写
-->
<property name="basePackage" value="com.spring.dao"/>
</bean>
<!--创建StudentService-->
<bean id="myStudentService" class="com.spring.service.StudentServiceImpl">
<property name="studentDao" ref="studentDao"/>
</bean>
</beans>
8、创建测试类,获取service对象,通过service调用dao完成数据库的访问
package com.spring;
import com.spring.dao.StudentDao;
import com.spring.entity.Student;
import com.spring.service.StudentService;
import com.spring.service.StudentServiceImpl;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppTest {
@Test
public void test01() {
String config = "classpath:applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(config);
// String[] names = context.getBeanDefinitionNames();
// for (String name : names) {
// System.out.println("容器中的对象名称:" + name+'|'+context.getBean(name));
// }
StudentService studentService = (StudentService) context.getBean("myStudentService", StudentServiceImpl.class);
/*插入数据*/
// Student student = new Student();
// student.setName("小红");
// student.setEmail("xiaohong@qq.com");
// student.setAge(22);
// System.out.println(studentService.addStudent(student));
/*查询*/
// studentService.queryStudents().forEach(n->System.out.println(n.toString()));
studentService.queryStudents();
/*
spring和mybatis整合后,事务是自动提交的,无需执行sqlSession.commit();
*/
}
}