前兩篇文章我從最原始的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框架。