MyBatis與Spring整合過(guò)程實(shí)例解析
這篇文章主要介紹了MyBatis與Spring整合過(guò)程實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
從之前的代碼中可以看出直接使用 MyBatis 框架的 SqlSession 訪問(wèn)數(shù)據(jù)庫(kù)并不簡(jiǎn)便。MyBatis 框架的重點(diǎn)是 SQL 映射文件,為方便后續(xù)學(xué)習(xí),本節(jié)講解 MyBatis 與 Spring 的整合。教程的后續(xù)講解中將使用整合后的框架進(jìn)行演示。
導(dǎo)入相關(guān)JAR包
1)MyBatis 框架所需的 JAR 包

圖 1MyBatis相關(guān)的JAR包
2)Spring 框架所需的 JAR 包
- aopalliance-1.0.jar
- aspectjweaver-1.6.9.jar
- spring-aop-3.2.13.RELEASE.jar
- spring-aspects-3.2.13.RELEASE.jar
- spring-beans-3.2.13.RELEASE.jar
- spring-context-3.2.13.RELEASE.jar
- spring-core-3.2.13.RELEASE.jar
- spring-expression-3.2.13.RELEASE.jar
- spring-jdbc-3.2.13.RELEASE.jar
- spring-tx-3.2.13.RELEASE.jar
3)MyBatis 與 Spring 整合的中間 JAR 包
該中間 JAR 包的版本為 mybatis-spring-1.3.1.jar,此版本可以從網(wǎng)址“http://mvnrepository.com/artifact/org.mybatis/mybatis-spring/1.3.1”下載。
4)數(shù)據(jù)庫(kù)驅(qū)動(dòng) JAR 包
教程所使用的Mybatis數(shù)據(jù)庫(kù)驅(qū)動(dòng)包為 mysql-connector-java-5.1.25-bin.jar。
5)數(shù)據(jù)源所需的 JAR 包
在整合時(shí)使用的是 DBCP 數(shù)據(jù)源,需要準(zhǔn)備 DBCP 和連接池的 JAR 包。
本教程所用版本的 DBCP 的 JAR 包為 commons-dbcp2-2.2.0.jar,可以從網(wǎng)址“htttp://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi”下載。
最新版本的連接池的 JAR 包為 commons-pool2-2.5.0.jar,可以從網(wǎng)址“http://commons.apache.org/proper/commons-pool/download_pool.cgi”下載。
在Spring中配置MyBatis工廠
通過(guò)與 Spring 的整合,MyBatis 的 SessionFactory 交由 Spring 來(lái)構(gòu)建,在構(gòu)建時(shí)需要在 Spring 的配置文件中添加如下代碼:
<!--配置數(shù)據(jù)源--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/springtest?seUnicode=true&characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="1128" /> <!-- 最大連接數(shù) --> <property name="maxTotal" value="30"/> <!-- 最大空閑連接數(shù) --> <property name="maxIdle" value="10"/> <!-- 初始化連接數(shù) --> <property name="initialSize" value="5"/> </bean> <!-- 配置SqlSessionFactoryBean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 引用數(shù)據(jù)源組件 --> <property name="dataSource" ref="dataSource" /> <!-- 引用MyBatis配置文件中的配置 --> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean>
使用 Spring 管理 MyBatis 的數(shù)據(jù)操作接口
使用 Spring 管理 MyBatis 數(shù)據(jù)操作接口的方式有多種,其中最常用、最簡(jiǎn)潔的一種是基于 MapperScannerConfigurer 的整合。該方式需要在 Spring 的配置文件中加入以下內(nèi)容:
<!-- Mapper代理開(kāi)發(fā),使用Spring自動(dòng)掃描MyBatis的接口并裝配 (Sprinh將指定包中的所有被@Mapper注解標(biāo)注的接口自動(dòng)裝配為MyBatis的映射接口) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- mybatis-spring組件的掃描器,com.dao只需要接口(接口方法與SQL映射文件中的相同) --> <property name="basePackage" value="com.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean>
項(xiàng)目結(jié)構(gòu)

第一步:entity層
public class City implements Serializable {
private long cid;
private String cname;
private long pid;
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public long getPid() {
return pid;
}
public void setPid(long pid) {
this.pid = pid;
}
}
第二步:Dao層
@MapperScan
public interface UserMapper {
public City getUserList(Integer cid);
}
第三步:service層
public interface UserService {
public City getUserList(Integer cid);
}
第四步:service實(shí)現(xiàn)層
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;//聲明UserMapper接口引用
@Override
public City getUserList(Integer cid) {
return userMapper.getUserList(cid);
}
}
第五步:CityMapper.xml
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTO Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.smbms.dao.UserMapper">
<!--查-->
<select id="getUserList" resultType="cn.smbms.entity.City"><!--resultMap屬性值指向resultMap節(jié)點(diǎn)的ID-->
select * from city where cid=#{cid}
</select>
</mapper>
第六步:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--根節(jié)點(diǎn)是我們的beans節(jié)點(diǎn)-->
<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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- 自動(dòng)掃描 -->
<context:component-scan base-package="cn.smbms" />
<!-- 引入配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 數(shù)據(jù)源配置-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--別名-->
<property name="typeAliasesPackage" value="cn.smbms.entity"/>
<!-- 自動(dòng)掃描mapping.xml文件,**表示迭代查找 -->
<property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean>
<!-- DAO接口所在包名,Spring會(huì)自動(dòng)查找其下的類 ,包下的類需要使用@MapperScan注解,否則容器注入會(huì)失敗 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.smbms.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- (事務(wù)管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
第七步:jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?useUniCode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=root
第八步:mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- xml文件的頭文件,起到對(duì)文件的約束作用(例如:必須存在哪些節(jié)點(diǎn)) -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--核心配置-->
</configuration>
第九步:測(cè)試
@Test
public void shouldAnswerWithTrue()
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService)ctx.getBean("userService");
City userList = userService.getUserList(130000);
System.out.println(userList.getCname());
}
以上代碼是基于注解,如果想要XML方式,下面就是,謝謝根據(jù)上面的進(jìn)行修改:修改applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--根節(jié)點(diǎn)是我們的beans節(jié)點(diǎn)-->
<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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- 自動(dòng)掃描 -->
<context:component-scan base-package="cn.smbms" />
<!-- 引入配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 數(shù)據(jù)源配置-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--別名-->
<property name="typeAliasesPackage" value="cn.smbms.entity"/>
<!-- 自動(dòng)掃描mapping.xml文件,**表示迭代查找 -->
<property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean>
<!-- DAO接口所在包名,Spring會(huì)自動(dòng)查找其下的類 ,包下的類需要使用@MapperScan注解,否則容器注入會(huì)失敗 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.smbms.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<bean id="userService" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.smbms.dao.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- Service層-->
<bean id="iBankService" class="cn.smbms.service.impl.UserServiceImpl">
<property name="UserMapper" ref="userService"/>
</bean>-->
<!-- (事務(wù)管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
修改Dao層
public interface UserMapper {
public City getUserList(Integer cid);
}
修改Service實(shí)現(xiàn)類
public class UserServiceImpl implements UserService {
public UserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
private UserMapper userMapper;//聲明UserMapper接口引用
@Override
public City getUserList(Integer cid) {
return userMapper.getUserList(cid);
}
}
以上都是對(duì)Spring和Mybatis進(jìn)行整合,希望對(duì)你有一些幫助,謝謝
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 5分鐘快速學(xué)會(huì)spring boot整合Mybatis的方法
- Spring Boot整合tk.mybatis代碼實(shí)例
- SpringBoot 整合jdbc和mybatis的方法
- SpringBoot整合MyBatis實(shí)現(xiàn)樂(lè)觀鎖和悲觀鎖的示例
- SpringBoot整合MyBatis-Plus3.1教程詳解
- 使用maven整合Spring+SpringMVC+Mybatis框架詳細(xì)步驟(圖文)
- Spring Boot整合MyBatis連接Oracle數(shù)據(jù)庫(kù)的步驟全紀(jì)錄
- Spring Boot整合mybatis并自動(dòng)生成mapper和實(shí)體實(shí)例解析
- spring 整合 mybatis 中數(shù)據(jù)源的幾種配置方式(總結(jié)篇)
相關(guān)文章
在MyBatis中實(shí)現(xiàn)一對(duì)多查詢和多對(duì)一查詢的方式詳解(各兩種方式)
今天通過(guò)兩種方法分別給大家介紹在MyBatis中實(shí)現(xiàn)一對(duì)多查詢和多對(duì)一查詢的方式,每種方式通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-01-01
elasticsearch源碼分析index?action實(shí)現(xiàn)方式
這篇文章主要為大家介紹了elasticsearch源碼分析index?action實(shí)現(xiàn)方式,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04
spring注解如何為bean指定InitMethod和DestroyMethod
這篇文章主要介紹了spring注解如何為bean指定InitMethod和DestroyMethod,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
Java子類實(shí)例化總是默認(rèn)調(diào)用父類的無(wú)參構(gòu)造操作
這篇文章主要介紹了Java子類實(shí)例化總是默認(rèn)調(diào)用父類的無(wú)參構(gòu)造操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10
Java實(shí)現(xiàn)PIFrame窗體效果的示例代碼
在很多現(xiàn)代應(yīng)用中,常常需要使用個(gè)性化的窗體外觀,擺脫傳統(tǒng)窗口邊框的限制,無(wú)邊框、透明、圓角和陰影效果使得窗體顯得更輕巧、更具視覺(jué)吸引力,同時(shí)允許用戶自由拖拽和??看绑w,所以本文給大家介紹了如何使用Java實(shí)現(xiàn)PIFrame窗體效果,需要的朋友可以參考下2025-03-03
java判斷請(qǐng)求是來(lái)自PC端還是手機(jī)端小技巧
這篇文章主要為大家介紹了java判斷請(qǐng)求是來(lái)自PC端還是手機(jī)端小技巧,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
Java?超詳細(xì)講解設(shè)計(jì)模式之原型模式講解
原型模式是用于創(chuàng)建重復(fù)的對(duì)象,同時(shí)又能保證性能。這種類型的設(shè)計(jì)模式屬于創(chuàng)建型模式,它提供了一種創(chuàng)建對(duì)象的最佳方式,今天通過(guò)本文給大家介紹下Java?原型設(shè)計(jì)模式,感興趣的朋友一起看看吧2022-03-03
java實(shí)現(xiàn)隨機(jī)生成驗(yàn)證碼圖片
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)隨機(jī)生成驗(yàn)證碼圖片,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-12-12
cmd中javac和java使用及注意事項(xiàng)詳解
這篇文章主要介紹了cmd中javac和java使用及注意事項(xiàng)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07

