spring(三) spring與mybatis整合
作為Bean容器,spring框架提供了IOC機制,可以接管所有元件的建立工作,並管理,整合的主要目標就是將mybatis的核心元件方放到spring中。
具體的是mybatis的核心是獲取sqlSession物件,而sqlSession物件依賴於SqlSessionFactroy例項,而SqlSessionFactroy例項依賴於SqlSessionFactoryBuilder,Spring通過讀取mybatis的配置檔案,構建這些元件,管理這些元件的生命週期。
一、階段一:通過sqlSessionTemplate實現
1. 建立實體類Student
package com.pojo; public class Student { private String id; private String name; private String address; private int age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Student(String id, String name, String address, int age) { super(); this.id = id; this.name = name; this.address = address; this.age = age; } public Student() { super(); } }
2. 建立訪問介面StudentDao
package com.dao;
import java.util.List;
import com.pojo.Student;
public interface StudentDao {
public int getCount(); //查詢總數
public List<Student> getStuList(); //返回所有資訊
public int insert(Student stu); //插入資訊
}
3. 建立sql對映檔案StudentMapper.xml
<?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.dao.StudentDao"> <resultMap type="Student" id="stuList"> <result property="id" column="id"/> <result property="name" column="name"/> <result property="address" column="address"/> <result property="age" column="age"/> </resultMap> <select id="getCount" resultType="int"> select count(1) from student </select> <select id="getStuList" resultMap="stuList"> select * from student </select> <insert id="insert" parameterType="Student"> insert into student values (#{id},#{name},#{address},#{age}) </insert> </mapper>
4. 配置mybatis-config.xml檔案
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mbatis-3-config.dtd"> <configuration> <!-- 1.設定執行時的行為,本次新增日誌記錄 --> <settings> <!-- 設定日誌記錄 --> <setting name="logImpl" value="LOG4J"/> <setting name="autoMappingBehavior" value="NONE"/> </settings> <!-- 2.為類定義別名 --> <typeAliases> <!-- 指定包名pojo,MyBatis會自動掃描下面的JavaBean --> <package name="com.pojo"/> </typeAliases> </configuration>
可以看到,將資料來源和mapper對映檔案去掉了,我們一會在 spring 的 applicationContext.xml 配置這些。
5. 建立業務實現類StudentDaoImpl
package com.service;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import com.dao.StudentDao;
import com.pojo.Student;
public class StudentDaoImpl implements StudentDao {
private SqlSessionTemplate sqlSession;
public SqlSessionTemplate getSqlSession() {
return sqlSession;
}
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return sqlSession.selectOne("com.dao.StudentDao.getCount"); //這種一般不用,用下邊的Mapper繫結的
}
@Override
public List<Student> getStuList() {
// TODO Auto-generated method stub
return sqlSession.getMapper(StudentDao.class).getStuList();
}
@Override
public int insert(Student stu) {
// TODO Auto-generated method stub
return sqlSession.getMapper(StudentDao.class).insert(stu);
}
}
sqlSesionTemplate代替了原來的SqlSession來操作資料庫會話,它實現類mybatis的SqlSession介面,可以更好的配合spring進行管理。
6. 配置主要的applicationContext.xml檔案,進行整合
<?xml version="1.0" encoding="UTF-8"?>
<!-- p:p名稱空間;context:註解;aop:aop增強;tx:事務管理 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">
<!-- 1.配置資料來源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
<property name="username" value="xudong"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 2.配置SqlSessionfactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/> <!--引入資料來源元件 -->
<property name="configLocation" value="classpath:mybatis-spring-config.xml"/> <!-- 載入batis核心配置檔案 -->
<property name="mapperLocations">
<list><value>classpath:com/dao/*.xml</value></list>
</property>
</bean>
<!-- 3. 配置sqlSessionTemplate -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg>
<ref bean="sqlSessionFactory"/>
</constructor-arg>
</bean>
<!-- 4. 為Dao元件注入sqlSessionTemplate 例項 -->
<bean id="StudentDaoImpl" class="com.service.StudentDaoImpl">
<property name="sqlSession" ref="sqlSessionTemplate"></property>
</bean>
</beans>
我們的目的就是為了獲得SqlSessionTemplate例項,並裝配到業務實現類中,具體步驟很簡單,就是通過引入資料來源和mapper對映,獲得sqlSessonFactory,其中SqlSessionFactoryBean封裝了SqlSessionFactoryBuilder例項化工廠的過程。然後利用工廠物件例項化SqlSessionTemplate。
為了方便可以引入外部資料來源,上邊的配置可以更改如下:
<?xml version="1.0" encoding="UTF-8"?>
<!-- p:p名稱空間;context:註解;aop:aop增強;tx:事務管理 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">
<!-- 1.配置資料來源 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:database.properties"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${userName}"></property>
<property name="password" value="${password}"></property>
</bean>
<!-- 2.配置SqlSessionfactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/> <!--引入資料來源元件 -->
<property name="configLocation" value="classpath:mybatis-spring-config.xml"/> <!-- 載入batis核心配置檔案 -->
<property name="mapperLocations">
<list><value>classpath:com/dao/*.xml</value></list>
</property>
</bean>
<!-- 3. 配置sqlSessionTemplate -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg>
<ref bean="sqlSessionFactory"/>
</constructor-arg>
</bean>
<!-- 4. 為Dao元件注入sqlSessionTemplate 例項 -->
<bean id="StudentDaoImpl" class="com.service.StudentDaoImpl">
<property name="sqlSession" ref="sqlSessionTemplate"></property>
</bean>
</beans>
同時增加資料庫配置的properties檔案
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
userName=xudong
password=123456
6. 測試
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentDao stuDao=(StudentDao)ac.getBean("StudentDaoImpl");
System.out.println("查詢 getCount() 總數為: "+stuDao.getCount());
List<Student> stuList = stuDao.getStuList();
System.out.println(stuList);
}
結果為:
查詢 getCount() 總數為: 12 [[email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]]