1. 程式人生 > >【MyBatis框架】mybatis和spring整合

【MyBatis框架】mybatis和spring整合

spring和mybatis整合

1.整合思路

需要spring通過單例方式管理SqlSessionFactory。
spring和mybatis整合生成代理物件,使用SqlSessionFactory建立SqlSession。(spring和mybatis整合自動完成)
持久層的mapper都需要由spring進行管理。

2.整合環境
建立一個新的java工程(接近實際開發的工程結構)

jar包:
mybatis3.2.7的jar包
spring3.2.0的jar包
mybatis和spring的整合包:早期ibatis和spring整合是由spring官方提供,mybatis和spring整合由mybatis提供。jar包名mybatis-spring-1.2.2.jar

下面加入MyBatis與Spring整合的全部jar包

如圖



工程結構:

如圖




3.sqlSessionFactory
在applicationContext.xml配置sqlSessionFactory和資料來源

sqlSessionFactory在mybatis和spring的整合包下。
<?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:mvc="http://www.springframework.org/schema/mvc"
	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-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">


	<!-- 載入配置檔案 -->
	<context:property-placeholder location="classpath:db.properties" />


	<!-- 資料來源,使用dbcp -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="10" />
		<property name="maxIdle" value="5" />
	</bean>




	<!-- sqlSessinFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 載入mybatis的配置檔案 -->
		<property name="configLocation" value="mybatis/SqlMapConfig.xml" />
		<!-- 資料來源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
</beans>

4.原始dao開發(和spring整合後)
4.1User.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">


<!-- namespace名稱空間,作用就是對sql進行分類化管理,理解sql隔離
注意:使用mapper代理方法開發,namespace有特殊重要的作用 -->
<mapper namespace="test">
	<!-- 在對映檔案中配置很多sql語句 -->
	
	<!-- 需求:通過id查詢使用者表的記錄 -->
	<!-- 通過select執行資料庫查詢,
	     id:標示對映檔案中的sql,成為Statement的id 
	     將sql語句封裝到mappedStatement物件中,所以將id稱為statement的id,
	     
	     parameterType:指定輸入引數的型別,
	     
	     #{}標示一個佔位符,
	     
	     #{id}其中id表示接收輸入引數的名稱,如果輸入引數是簡單型別,那麼#{}中的值可以任意(如value)。
	     
	     resultType:指定sql輸出結果的對映的java物件型別,
	     select指定resultType表示將單條記錄對映成java物件-->	
	<select id="findUserById" parameterType="int" resultType="cn.edu.hpu.ssm.po.User">
	  SELECT * FROM USER WHERE id=#{id}
	</select>
	
</mapper>

在SqlMapconfig.xml中載入User.xml
<!-- 載入對映檔案 -->
<mappers>
	<!-- 通過resource方法一次載入一個對映檔案 -->
	<mapper resource="sqlmap/User.xml"/>
	
	<!-- 批量載入mapper-->
	<package name="cn.edu.hpu.ssm.mapper"/>
</mappers>

4.2dao(實現類繼承SqlSessionDaoSupport)

dao介面實現類需要注入SqlSessoinFactory,通過spring進行注入。
這裡spring宣告配置方式,配置dao的bean:

讓UserDaoImpl實現類繼承SqlSessionDaoSupport

4.3配置dao
首先建立UserDao介面和UserDaoImpl介面實現
UserDao.java:
package cn.edu.hpu.ssm.dao;

import cn.edu.hpu.ssm.po.User;

//使用者管理的Dao介面
public interface UserDao{
	
	//根據Id查詢使用者資訊
	public User findUserById(int id) throws Exception;
}

UserDaoImpl.java:
package cn.edu.hpu.ssm.dao;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.edu.hpu.ssm.po.User;

public class UserDaoImpl implements UserDao{


	//需要向dao實現類中注入SqlSessionFactory工廠
	//這裡我們暫時沒用spring,我們通過構造方法注入
	private SqlSessionFactory sqlSessionFactory;
	public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
		this.sqlSessionFactory=sqlSessionFactory;
	}


	public User findUserById(int id) throws Exception {
		SqlSession sqlSession=sqlSessionFactory.openSession();
		
		User user=sqlSession.selectOne("test.findUserById",id);
		
		//釋放資源
		sqlSession.close();
		return user;
	}
}

在applicationContext.xml中配置dao。
<?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:mvc="http://www.springframework.org/schema/mvc"
	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-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">


	<!-- 載入配置檔案 -->
	<context:property-placeholder location="classpath:db.properties" />


	<!-- 資料來源,使用dbcp -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="10" />
		<property name="maxIdle" value="5" />
	</bean>




	<!-- sqlSessinFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 載入mybatis的配置檔案 -->
		<property name="configLocation" value="mybatis/SqlMapConfig.xml" />
		<!-- 資料來源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!-- 原始Dao介面 -->
	<bean id="userDao" class="cn.edu.hpu.ssm.dao.UserDaoImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
	
	
</beans>

讓UserDaoImpl去繼承SqlSessionDaoSupport類,在SqlSessionDaoSupport類中提供了set和getsqlSessionFactory的方法。
package cn.edu.hpu.ssm.dao;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;


import cn.edu.hpu.ssm.po.User;


public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{


	public User findUserById(int id) throws Exception {
		//繼承SqlSessionDaoSupport類,通過this.getSqlSession()得到sqlSession
		SqlSession sqlSession=this.getSqlSession();
		
		User user=sqlSession.selectOne("test.findUserById",id);
		
		return user;
	}
}

4.4測試程式
package cn.edu.hpu.ssm.test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import cn.edu.hpu.ssm.dao.UserDao;
import cn.edu.hpu.ssm.po.User;


public class UserDaoImplTest {
	
	private ApplicationContext applicationContext;
	
	//註解Before是在執行本類所有測試方法之前先呼叫這個方法
	@Before
	public void setup() throws Exception{
		applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
		
	}
	
	@Test
	public void testFindUserById() throws Exception{
		UserDao userDao=(UserDao)applicationContext.getBean("userDao");
		
		//呼叫UserDao的方法
		User user=userDao.findUserById(1);
		//輸出使用者資訊
		System.out.println(user.getId()+":"+user.getUsername());
	}
	
}

測試結果和輸出日誌:
DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [[email protected]] was not registered for synchronization because synchronization is not active
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - JDBC Connection [jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8, [email protected], MySQL-AB JDBC Driver] will not be managed by Spring
DEBUG [main] - ==> Preparing: SELECT * FROM USER WHERE id=? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
DEBUG [main] - Closing non transactional SqlSession [[email protected]]
DEBUG [main] - Returning JDBC Connection to DataSource
1:張明明

5.mapper代理開發
5.1mapper.xml和mapper.java
UserMapper.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="cn.edu.hpu.ssm.mapper.UserMapper">
	
	<select id="findUserById" parameterType="int" resultType="cn.edu.hpu.mybatis.po.User">
	  SELECT * FROM USER WHERE id=#{id}
	</select>
	
</mapper>

UserMapper.java:
package cn.edu.hpu.ssm.mapper;

import cn.edu.hpu.ssm.po.User;

//使用者管理的Dao介面
public interface UserMapper {
	
	//根據Id查詢使用者資訊
	public User findUserById(int id) throws Exception;
}

5.2通過MapperFactoryBean建立代理物件
<!-- mapper配置 
	MapperFactoryBean根據mapper介面生成mapper代理物件-->
	<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<!-- mapperInterface指定mapper介面 -->
		<property name="mapperInterface" value="cn.edu.hpu.ssm.mapper.UserMapper"/>
		<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
	</bean>

此方法問題:
需要針對每個mapper進行配置,麻煩。所以要通過MapperScannerConfigurer進行mapper掃描。

5.3通過MapperScannerConfigurer進行mapper掃描(建議使用)
<!-- mapper批量掃描,從mapper包中掃描出mapper介面,自動建立代理物件並且在spring容器中注入 
	遵循規範:將mapper.java和mapper.xml對映檔名稱保持一致,且在一個目錄中.
	自動掃描出來的mapper的bean的id為mapper類名(首字母小寫)-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<!-- 指定掃描的包名
	如果掃描多個包,每個包中間使用半形逗號分隔 -->
	<property name="basePackage" value="cn.edu.hpu.ssm.mapper"/>
	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

sqlMapperConfig.xml中的mapper掃描就可以不要了
<!-- 載入對映檔案 -->
<mappers>
	<!-- 通過resource方法一次載入一個對映檔案 -->
	<mapper resource="sqlmap/User.xml"/>
	
	<!-- 批量載入mapper
		
	和spring整合後,使用mapper掃描器,這裡不需要配置了-->
	<!--<package name="cn.edu.hpu.ssm.mapper"/>-->
</mappers>

5.4測試程式碼
package cn.edu.hpu.ssm.test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import cn.edu.hpu.ssm.mapper.UserMapper;
import cn.edu.hpu.ssm.po.User;


public class UserMapperTest {


private ApplicationContext applicationContext;
	
	//註解Before是在執行本類所有測試方法之前先呼叫這個方法
	@Before
	public void setup() throws Exception{
		applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
		
	}
	
	@Test
	public void testFindUserById() throws Exception {
		UserMapper userMapper=(UserMapper)applicationContext.getBean("userMapper");
		User user=userMapper.findUserById(1);
		System.out.println(user.getId()+":"+user.getUsername());
		
	}


}

測試結果及輸出日誌:
DEBUG [main] - Returning cached instance of singleton bean 'userMapper'
DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [[email protected]] was not registered for synchronization because synchronization is not active
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - JDBC Connection [jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8, [email protected], MySQL-AB JDBC Driver] will not be managed by Spring
DEBUG [main] - ==>  Preparing: SELECT * FROM USER WHERE id=? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - Closing non transactional SqlSession [[email protected]]
DEBUG [main] - Returning JDBC Connection to DataSource
1:張明明

相關推薦

SSH框架系列之 Spring 整合 Hibernate 框架

操作 enter pda 就是 負責 spring配置 1.0 port -s 1、SSH 三大框架整合原理 Spring 與 Struts2 的整合就是將 Action 對象交給 Spring 容器來負責創建。 Spring 與 Hibernate 的整合就是將

MyBatis框架mybatisspring整合

spring和mybatis整合 1.整合思路 需要spring通過單例方式管理SqlSessionFactory。 spring和mybatis整合生成代理物件,使用SqlSessionFactory建立SqlSession。(spring和mybatis整合自動完成)

持久化框架Mybatis與Hibernate的詳細對比

很大的 效率 myba 今天 http 目的 ping pin 增刪 作為一位優秀的程序員,只知道一種ORM框架是遠遠不夠的。在開發項目之前,架構的技術選型對於項目是否成功起到至關重要的作用。我們不僅要了解同類型框架的原理以及技術實現,還要深入的理解各自的優缺點,以便我們能

持久化框架Mybatis簡介與原理

什麼是Mybatis          MyBatis 本是apache的一個開源專案iBatis, 2010年這個專案由apache software foundation 遷移到了google code,並且改名為MyBatis 。iBATIS一詞來源於“internet

MyBatis框架Mybatis開發dao方法第一部分

下面來討論mybatis開發Dao的方法 先來說一下基本架構流程中使用到的幾個類 1.SqlSession使用範圍 1.1SqlSessionFactoryBuilder  通過SqlSessionFactoryBuilder建立會話工廠SqlSessionFactory

SSM-MyBatis框架MyBatis開發DAO的方式

Mybatis開發Dao的方式   MyBatis開發Dao有兩種方式:原始Dao的開發方式,Mapper動態代理的方式。     兩種開發方式在企業開發中均有運用。都要掌握。    使用myBatis時,需要對其進行一個全域性的管理配置。     sqlMappingCo

java框架MyBatis-Plus(1)--MyBatis-Plus快速上手開發及核心功能體驗

1.MyBatis-Plus入門開發及配置 1.1.MyBatis-Plus簡介 MyBatis-Plus(簡稱 MP)是一個 MyBatis的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。 MyBatis-Plus易於學習,官網提供了基於SpringBoot的中文文件,社

持久化框架SpringMVC+Spring4+Mybatis3整合,開發簡單Web專案+原始碼下載

      上篇博文我們介紹了mybatis的基本概念與原理,這篇博文我們通過Spring與Mybatis整合,開發一個簡單使用者增刪改查的Web專案。 基本準備工作 1、安裝JDK1.6以上版本,安裝與配置 4、Spring-4.0.0的版本 5、tomacat6

前端框架bootstrapeasyUI

    這兩天在寫一個專案,前端的介面是使用easyUI來完成的。寫完之後,嘗試使用bootstrap重新做了一次,首先要說的是在此之前沒用bootstrap寫過大的專案,只是曾用bootstrap寫過幾個小頁面。稍微說下自己使用bootstrap的感受吧。     先分別

MVC框架——ViewController之間的傳值

    在MVC中,Controller執行一個可以說是路由功能,它通過View傳過來的資料,來決定應該呼叫哪一個Model,同樣會把Model處理完的資料傳給View,所以就總是涉及到Control

java框架SpringBoot(3) -- SpringBoot整合Swagger2

1.SpringBoot web專案整合Swagger2 1.1.認識Swagger2 Swagger 是一個規範和完整的框架,用於生成、描述、呼叫和視覺化 RESTful 風格的 Web 服務。總體目標是使客戶端和介面文件系統作為伺服器以同樣的速度來更新。文件的介面方法,引數和模型緊密整合到伺服器端的程式

java框架SpringBoot(5)--SpringBoot整合分散式Dubbo+Zookeeper

1.理論概述 1.1.分散式 分散式系統是若干獨立計算機的集合,這些計算機對於使用者來講就像單個系統。 由多個系統整合成一個整體,提供多個功能,組合成一個板塊,使用者在使用上看起來是一個服務。(比如淘寶網)。   起源 分散式系統出現的原因是:用多個廉價的、普通的機器完成單個計算機無法完成的計算、儲

Mybatis Spring整合之原始dao開發

package settings 定義 int inter 實現 frame port tor F:\Aziliao\mybatis\代碼\31.mybatis與spring整合-開發原始dao 1.1. SqlMapConfig.xml <?xml version

Mybatis Spring整合之mapper代理開發

dtd des mes factor ssi fig 隔離 代理 location F:\1ziliao\mybatis\代碼 1.1 SqlMapConfig.xml <?xml version="1.0" encoding="UTF-8" ?><

MyBatis學習(三)---MyBatisSpring整合

session drive beans xmla 連接 加載 test 方法 bsp 想要了解MyBatis基礎的朋友可以通過傳送門:   MyBatis學習(一)---配置文件,Mapper接口和動態SQL  http://www.cnblogs.com/ghq120/p

十一、mybatisspring整合

tor .class 持久 source 字母 HERE code 掃描 method 想要整合mybatis和spring,那麽我們首先要知道這兩個框架是幹嘛的,對於mybatis我們前面幾篇博客已經有了很詳細的介紹,我們通過加載mybatis-configuratio

深入淺出Mybatis(十)MybatisSpring整合

整合過程 整合思路  1. 建立新的java Project      2. 匯入整合所需要的jar包(包括mybatis、spring、整合jar、資料庫連線等),下載點選這裡。      3.

MyBatisSpring整合

ner his not springmvc ole load ade 資源 sco Spring MyBatis整合包 Spring 解壓 然後導入Mybatis包。 最後狀態: 上面導入了SSM的相關jar包 另外需要整合包: 配置文件: 與web.

框架Mybatis 01 原生態JDBC的問題&Mybatis架構

原生JDBC的問題總結: 1、資料庫連線,使用時就建立,不使用立即釋放,對資料庫進行頻繁開啟和關閉,造成資料庫資源浪費,影響資料庫效能。 解決:使用資料庫連線池管理資料庫連線 2、將sql語句硬編碼到java程式碼中,如果修改sql語句,需要重新編譯java程式碼,不利

框架mybatis 開發dao方法---mapper代理開發

mapper代理的開發 1、需要編寫mapper.xml對映檔案 2、需要編寫mapper.java介面檔案(mapper.java相當於dao介面) 1、接下來我們先將之前的mapper.xml對映檔案拷貝下來: <mapper namespace="co