Spring集成Mybatis過程詳細講解
為啥學(xué)習(xí)集成Mybatis ORM框架
雖然Spring中提供了JDBCTemplate模塊,已經(jīng)很大程度了解決了JDBC代碼的復(fù)雜度,但它仍然是和Java代碼寫在一起的。反觀 Mybatis 將 Sql 語句寫在配置文件中,使得SQL語句和程序?qū)崿F(xiàn)了松耦合。而且提供了些許標(biāo)簽,使得SQL可以是動態(tài)的。在ORM基礎(chǔ)上想要更好的用Spring的DI、AOP、事務(wù)處理、Junit支持等實現(xiàn)成果,學(xué)會使用 Spring 框架集成 Mybatis 是大勢所趨。
實現(xiàn)步驟
第一步:準(zhǔn)備數(shù)據(jù)庫表
第二步:IDEA中創(chuàng)建一個模塊,并引入以下依賴
- spring-context
- spring-jdbc
- mysql驅(qū)動
- 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)實現(xiàn),所以提前創(chuàng)建好所有的包
- XXXX.mapper
- XXXX.service
- XXXX.service.impl
- XXXX.bean
第四步:編寫bean
Account,按bean規(guī)范創(chuàng)建
第五步:編寫Mapper接口
AccountMapper接口,定義與數(shù)據(jù)庫交互的方法
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); }
第六步:編寫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>
第七步:編寫service接口和service接口的實現(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實現(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ù)庫 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ù)是否實現(xiàn)成功 if(cnt!=2) throw new RuntimeException("轉(zhuǎn)賬失敗"); } }
第八步:編寫jdbc.properties配置文件
數(shù)據(jù)庫連接池相關(guān)信息
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/???
jdbc.username=???
jdbc.password=???
第九步:編寫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> <!--駝峰命名自動映射,默認(rèn)false--> <setting name="mapUnderscoreToCamelCase" value="false"/> <!--設(shè)置懶加載--> <setting name="lazyLoadingEnabled" value="true"/> <!--配置日志,可以幫助我們查看sql執(zhí)行信息--> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> </configuration>
第十步:編寫spring.xml配置文件
組件掃描
引入外部的屬性文件
數(shù)據(jù)源
SqlSessionFactoryBean配置(注入mybatis核心配置文件路徑,指明別名包,注入數(shù)據(jù)源)
Mapper掃描配置器(指定掃描的包)
事務(wù)管理器(DataSourceTransactionManager,注入數(shù)據(jù)源)
啟動事務(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> <!--啟動事務(wù)注解--> <tx:annotation-driven transaction-manager="txManager"/> </beans>
第十一步:編寫測試程序,并添加事務(wù),進行測試。
@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); }
測試結(jié)果
到此這篇關(guān)于Spring集成Mybatis過程詳細講解的文章就介紹到這了,更多相關(guān)Spring集成Mybatis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何在springMVC的controller中獲取request
這篇文章主要介紹了如何在springMVC的controller中獲取request,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12SpringCloud?Gateway?DispatcherHandler調(diào)用方法詳細介紹
我們第一個關(guān)注的類就是DispatcherHandler,這個類提供的handle()方法,封裝了我們之后所有的handlerMappings,這個DispatcherHandler有點想SpringMVC的DispatchServlet,里面也是封裝了請求和對應(yīng)的處理方法的關(guān)系2022-10-10聊聊ResourceBundle和properties讀取配置文件的區(qū)別
這篇文章主要介紹了ResourceBundle和properties讀取配置文件的區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07springboot實現(xiàn)返回視圖而不是string的方法
這篇文章主要介紹了springboot實現(xiàn)返回視圖而不是string的方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01Spring Security OAuth2 授權(quán)碼模式的實現(xiàn)
這篇文章主要介紹了Spring Security OAuth2 授權(quán)碼模式的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08Spring boot測試找不到SpringRunner.class的問題
這篇文章主要介紹了Spring boot測試找不到SpringRunner.class的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01