前两篇文章我从最原始的JDBC的使用到一步一步搭建Mybatis的使用。这篇文章我将使用Spring整合Mybatis,本篇文章主要分为两部分:(1)Spring框架的单独搭建使用(2)Spring整合Mybatis。
Spring的单独使用
1.Spring的简单介绍
Spring是一个轻量级框架,主要用来降低程序的耦合度,作为第三方,管理Bean对象。Spring的两个核心是(1)IOC容器:扫描配置文件指定的类,反射生成实例对象,放置在容器中,供其他程序获取。IOC容器统一管理对象,避免了调用程序直接创建对象,降低了程序的耦合度。(2)DI依赖注入:Spring框架中程序获取IOC容器中对象的方式为依赖注入,即调用程序加注解,声明此处需要一个实现类,而Spring会注入到声明变量处。
2.环境准备
(1)引入Spring的核心jar包
<!--开始引入Spring,整合Spring -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--为jdbc、hibernate、jdo、jpa等提供一整的声明式和编程式事务管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
(2)编写Spring的配置文件,指定Spring需要扫描的包:
ApplicationContext.xml(这个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
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置Spring扫描哪些包,那么指定包下的所有带有注解的类将会被实例化到Spring容器中 -->
<context:component-scan base-package="TheFourthStep" />
<!--或者直接将指定类实例化为Bean对象存储到Spring容器中 -->
<bean id="entity" class="TheFourthStep.TestEntity">
</bean>
</beans>
3.运行测试
一、实体类
package TheFourthStep;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
@Repository("entity")
public class TestEntity {
public void speaking()
{
System.out.println("测试Speaking");
}
public void singing()
{
System.out.println("测试Singsing");
}
}
二、使用Bean对象
(1)直接从容器中取出Bean对象:
package TheFourthStep;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;
@Repository
public class SpringTest {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:ApplicationContext.xml");
TestEntity testEntity=(TestEntity)ac.getBean("entity") ;
testEntity.singing();
testEntity.speaking();
}
}
这种方式是直接从Application中取出Bean对象使用。
(2)Spring自动注入:
其他类的域为TestEntity类的变量,使用AutoWired注解
package TheFourthStep;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
@Repository("autowiredTest")
public class AutowiredTest {
@Autowired
private TestEntity entity;
public void testAutoWired()
{
entity.speaking();
}
}
调用:
package TheFourthStep;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;
@Repository
public class SpringTest {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:ApplicationContext.xml");
AutowiredTest autowiredTest=(AutowiredTest) ac.getBean("autowiredTest");
autowiredTest.testAutoWired();
}
}
AutowiredTest 类的testAutoWired使用了TestEntity 的实例对象,加了注解的TestEntity变量 直接由Spring注入实体对象。
4.总结
可以看到,使用Spring帮我们节省了创建对象的操作并且还降低了程序的耦合。当我们使用Spring整合Mybatis时,也可以帮我们省去许多创建对象的操作。
Spring整合Mybatis
整合之前,再回顾一下Mybatis操作数据库的操作(以查询操作为例):
public static void show()throws Exception
{
InputStream in=Resources.getResourceAsStream("Mybatis-config.xml");
SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(in);
SqlSession session=sqlSessionFactory.openSession();
StudentMapper studentMapper=session.getMapper(StudentMapper.class);
List<StudentEntity> list=studentMapper.selectAll();
for (StudentEntity entity : list) {
System.out.println(entity);
}
session.close();
in.close();
}
(1)通过扫描配置文件(关于数据库的连接信息等以及构造mapper实现类的信息)构造一个SqlSessionFactory,用来生产SqlSesiion。
(2)通过SqlSessionFactory生产Sqlsession。
(3)通过Sqlsession获取mapper接口的实现类(封装了JDBC)。
那么使用Spring整合Mybatis就是使用Spring管理上述过程:
将创建SqlSessionFactory实例、Sqlsession实例以及mapper实例的工作交由Spring。然后直接在声明mapper变量处加注解从Spring容器中获取实例对象。
1.环境准备
Spring整合mybatis的jar包
<!-- Spring整合Mybatis的jar包-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
Spring关于Mybatis的配置的xml
Spring-dao.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
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置整合mybatis过程 -->
<!-- 数据库连接池 其中,JDBC的属性参数可以单独写一条properties文件,然后在此引用-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/october?characterEncoding=utf8&useSSL=false"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描entity包 使用别名 -->
<property name="typeAliasesPackage" value="com.test.entity"/>
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.test.mapper"/>
</bean>
</beans>
2.代码执行
因为前边SqlSessionFactory、SqlSession甚至mapper的实例对象都不需要我们创建,当我们需要mapper的实例对象时,直接从Spring的容器获取就可以了。
package TheFourthStep;
import Entity.StudentEntity;
import Mapper.StudentMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class Main {
public static void main(String[] args)throws Exception {
//执行Spring加载过程
ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:spring-dao.xml");
StudentMapper mapper=(StudentMapper) ac.getBean(StudentMapper.class);
List<StudentEntity> studentList=mapper.selectAll();
for (StudentEntity studentEntity : studentList) {
System.out.println(studentEntity);
}
}
}
结果:
如果我需要AutoWired获取mapper对象,前提是声明mapper变量的类实例对象也是由Spring创建的,否则无法完成注入。
3.总结
Mybatis由Spring整合后,中间复杂创建Sqlsession等的过程全部交由Spring处理,省去很多步骤,也降低了程序的耦合度。
OK,到这里,Spring整合Mybatis就完成了,后续我会整合SpringMvc,完整生成一套SSM框架。