Spring集成Mybatis過(guò)程詳細(xì)講解
為啥學(xué)習(xí)集成Mybatis ORM框架
雖然Spring中提供了JDBCTemplate模塊,已經(jīng)很大程度了解決了JDBC代碼的復(fù)雜度,但它仍然是和Java代碼寫(xiě)在一起的。反觀 Mybatis 將 Sql 語(yǔ)句寫(xiě)在配置文件中,使得SQL語(yǔ)句和程序?qū)崿F(xiàn)了松耦合。而且提供了些許標(biāo)簽,使得SQL可以是動(dòng)態(tài)的。在ORM基礎(chǔ)上想要更好的用Spring的DI、AOP、事務(wù)處理、Junit支持等實(shí)現(xiàn)成果,學(xué)會(huì)使用 Spring 框架集成 Mybatis 是大勢(shì)所趨。
實(shí)現(xiàn)步驟
第一步:準(zhǔn)備數(shù)據(jù)庫(kù)表
第二步:IDEA中創(chuàng)建一個(gè)模塊,并引入以下依賴
- spring-context
- spring-jdbc
- mysql驅(qū)動(dòng)
- mybatis
- mybatis-spring:
mybatis提供的
與spring框架集成的依賴 - druid:德魯伊連接池
- junit
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>6.0.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>6.0.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.31</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.11</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> </dependencies>
第三步:基于三層架構(gòu)實(shí)現(xiàn),所以提前創(chuàng)建好所有的包
- XXXX.mapper
- XXXX.service
- XXXX.service.impl
- XXXX.bean
第四步:編寫(xiě)bean
Account,按bean規(guī)范創(chuàng)建
第五步:編寫(xiě)Mapper接口
AccountMapper接口,定義與數(shù)據(jù)庫(kù)交互的方法
package com.ncpowernode.spring.mappers; import com.ncpowernode.spring.bean.Account; import java.util.List; public interface AccountMapper { List<Account> selectAll(); Account selectByActno(String actno); int insert(Account account); int deleteByActno(String actno); int update(Account account); }
第六步:編寫(xiě)mapper配置文件
<?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.ncpowernode.spring.mappers.AccountMapper"> <select id="selectAll" resultType="account"> select * from t_act; </select> <insert id="insert"> insert into t_act values(#{actno},#{balance}) </insert> <delete id="deleteByActno"> delete from t_act where actno = #{actno}; </delete> <select id="selectByActno" resultType="account"> select * from t_act where actno = #{actno}; </select> <update id="update"> update t_act set balance = #{balance} where actno = #{actno}; </update> </mapper>
第七步:編寫(xiě)service接口和service接口的實(shí)現(xiàn)類
service接口
package com.ncpowernode.spring.service; import com.ncpowernode.spring.bean.Account; import java.util.List; public interface AccountService { int save(Account act); int deleteByActno(String actno); List<Account> getAll(); void transfer(String fromActno,String toActno,double money); }
service實(shí)現(xiàn)
package com.ncpowernode.spring.service.impl; import com.ncpowernode.spring.bean.Account; import com.ncpowernode.spring.mappers.AccountMapper; import com.ncpowernode.spring.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import java.util.List; @Service("accountService") @Transactional public class AccountServiceImpl implements AccountService { @Autowired @Qualifier("accountMapper") private AccountMapper accountMapper; @Override public int save(Account act) { return accountMapper.insert(act); } @Override public int deleteByActno(String actno) { return accountMapper.deleteByActno(actno); } @Override public List<Account> getAll() { return accountMapper.selectAll(); } @Override public void transfer(String fromActno, String toActno, double money) { // 判斷余額 Account fromAccount = accountMapper.selectByActno(fromActno); if (fromAccount.getBalance()<money) throw new RuntimeException("余額不足"); // 更新數(shù)據(jù)庫(kù) Account toAccount = accountMapper.selectByActno(toActno); fromAccount.setBalance(fromAccount.getBalance()-money); toAccount.setBalance(toAccount.getBalance()+money); int cnt = accountMapper.update(fromAccount); cnt += accountMapper.update(toAccount); // 判斷業(yè)務(wù)是否實(shí)現(xiàn)成功 if(cnt!=2) throw new RuntimeException("轉(zhuǎn)賬失敗"); } }
第八步:編寫(xiě)jdbc.properties配置文件
數(shù)據(jù)庫(kù)連接池相關(guān)信息
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/???
jdbc.username=???
jdbc.password=???
第九步:編寫(xiě)mybatis-config.xml核心配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!--駝峰命名自動(dòng)映射,默認(rèn)false--> <setting name="mapUnderscoreToCamelCase" value="false"/> <!--設(shè)置懶加載--> <setting name="lazyLoadingEnabled" value="true"/> <!--配置日志,可以幫助我們查看sql執(zhí)行信息--> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> </configuration>
第十步:編寫(xiě)spring.xml配置文件
組件掃描
引入外部的屬性文件
數(shù)據(jù)源
SqlSessionFactoryBean配置(注入mybatis核心配置文件路徑,指明別名包,注入數(shù)據(jù)源)
Mapper掃描配置器(指定掃描的包)
事務(wù)管理器(DataSourceTransactionManager,注入數(shù)據(jù)源)
啟動(dòng)事務(wù)注解(注入事務(wù)管理器)
<?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" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--組件掃描--> <context:component-scan base-package="com.ncpowernode.spring.service"/> <!--引入外部的屬性文件--> <context:property-placeholder location="jdbc.properties"/> <!--數(shù)據(jù)源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <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> <!--配置SqlSessionFactoryBean--> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <!--注入數(shù)據(jù)源--> <property name="dataSource" ref="dataSource"/> <!--指定別名包--> <property name="typeAliasesPackage" value="com.ncpowernode.spring.bean"/> <!--指定mybatis核心配置文件--> <property name="configLocation" value="mybatis-config.xml"/> </bean> <!--配置Mapper掃描配置器--> <!--主要掃描mapper接口,生成代理類--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ncpowernode.spring.mappers"/> </bean> <!--事務(wù)管理器--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--啟動(dòng)事務(wù)注解--> <tx:annotation-driven transaction-manager="txManager"/> </beans>
第十一步:編寫(xiě)測(cè)試程序,并添加事務(wù),進(jìn)行測(cè)試。
@Test public void testSM(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); AccountService accountService = applicationContext.getBean("accountService", AccountServiceImpl.class); accountService.getAll().forEach(System.out::println); accountService.transfer("act-001","act-002",10000.0); }
測(cè)試結(jié)果
到此這篇關(guān)于Spring集成Mybatis過(guò)程詳細(xì)講解的文章就介紹到這了,更多相關(guān)Spring集成Mybatis內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何在springMVC的controller中獲取request
這篇文章主要介紹了如何在springMVC的controller中獲取request,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12SpringCloud?Gateway?DispatcherHandler調(diào)用方法詳細(xì)介紹
我們第一個(gè)關(guān)注的類就是DispatcherHandler,這個(gè)類提供的handle()方法,封裝了我們之后所有的handlerMappings,這個(gè)DispatcherHandler有點(diǎn)想SpringMVC的DispatchServlet,里面也是封裝了請(qǐng)求和對(duì)應(yīng)的處理方法的關(guān)系2022-10-10聊聊ResourceBundle和properties讀取配置文件的區(qū)別
這篇文章主要介紹了ResourceBundle和properties讀取配置文件的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07Java如何正確處理下載文件時(shí)HTTP頭的編碼問(wèn)題
這篇文章主要介紹了Java如何正確處理下載文件時(shí)HTTP頭的編碼問(wèn)題,2023-07-07
通常HTTP消息包括客戶機(jī)向服務(wù)器的請(qǐng)求消息和服務(wù)器向客戶機(jī)的響應(yīng)消息,今天來(lái)講解下正確處理下載文件時(shí)HTTP頭的編碼問(wèn)題,需要的朋友可以參考下springboot實(shí)現(xiàn)返回視圖而不是string的方法
這篇文章主要介紹了springboot實(shí)現(xiàn)返回視圖而不是string的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01Spring Security OAuth2 授權(quán)碼模式的實(shí)現(xiàn)
這篇文章主要介紹了Spring Security OAuth2 授權(quán)碼模式的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08Java設(shè)計(jì)模式七大原則之里氏替換原則詳解
在面向?qū)ο蟮某绦蛟O(shè)計(jì)中,里氏替換原則(Liskov Substitution principle)是對(duì)子類型的特別定義。本文將為大家詳細(xì)介紹Java設(shè)計(jì)模式七大原則之一的里氏替換原則,需要的可以參考一下2022-02-02Spring boot測(cè)試找不到SpringRunner.class的問(wèn)題
這篇文章主要介紹了Spring boot測(cè)試找不到SpringRunner.class的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01Java實(shí)現(xiàn)帶GUI的氣泡詩(shī)詞效果
這篇文章主要為大家介紹了如何利用Java實(shí)現(xiàn)帶GUI的氣泡詩(shī)詞效果,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Java有一定幫助,感興趣的可以了解一下2022-12-12