Spring 對 Mybatis 的整合思路
阿新 • • 發佈:2018-12-27
作為Bean容器,Spring框架提供了IoC機制,可以接管所有的元件的建立工作並進行依賴管理,整合的主要工作就是把Mybatis框架使用中所涉及的核心元件配置到Spring容器中,交給Spring和建立和管理。
具體來說,業務邏輯物件依賴基於Mybatis技術實現Dao物件,核心是獲取SqlSession例項,則需要依賴SqlSessionFactory而SqlSessionFactory是SqlSessionFactoryBuider依據Mybatis配置檔案中的資料來源、SQL對映檔案等資訊來構建的。
整合優勢:
Spring對Mybatis 進行整合,在對元件實現解耦的同時還能使Mybatis框架的使用變得更加方便和簡單。此外,通過Spring提供的宣告式事務等服務,能進一步簡化開發工作量,提高開發效率。
整合示例
1、資料庫建表新增測試資料
use mybatis; CREATE TABLE `user` ( `uId` int(4) NOT NULL AUTO_INCREMENT, `uName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `uPwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `account` decimal(10, 2) NOT NULL, PRIMARY KEY (`uId`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; INSERT INTO `user` VALUES (2, '張三', '123456', 123.00); INSERT INTO `user` VALUES (9, '李四', '123123', 123.93); INSERT INTO `user` VALUES (10, '王五', '123123', 200.93);
2、配置專案(重點)
連線資料庫的配置檔案:db.properties
//mysql驅動類 jdbc.driver=com.mysql.jdbc.Driver //mysql連線的url地址 jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8 //連線mysql資料庫的使用者名稱 jdbc.username=root //連線mysql資料庫的密碼 jdbc.password=xiaotong
spring核心配置檔案:spring.cfg.xml
<?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: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-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 掃描包中註解標註類 --> <context:component-scan base-package="dao,service,entity,aop"/> <!-- 引入資料庫配置檔案 db.properties --> <context:property-placeholder location="classpath:db.properties" /> <!-- 配置資料來源,使用dbcp資料庫連線池 --> <bean id="dataSource" class="org.apache.commons.dbcp2.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}" /> </bean> <!-- SqlSessionFactory配置 --> <!-- 讓Spring管理SqlSessionFactory使用mybatis和spring整合包中的 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 資料庫連線池 --> <property name="dataSource" ref="dataSource" /> <!-- 載入mybatis的全域性配置檔案 --> <property name="configLocation" value="classpath:mybatis.cfg.xml" /> <!--配置SQL對映檔案--> <property name="mapperLocations"> <list> <!--掃描mapper包下所有的xml格式的檔案--> <value>classpath:mapper/userMapper.xml</value> </list> </property> </bean> <!-- 使用MapperScannerConfigurer掃描指定包的介面,並自動生成MapperFactoryBean --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="dao"/> </bean> </beans>
mybatis 核心配置檔案:mybatis.cfg.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> <setting name="logImpl" value="LOG4J"/> <!--設定為FULL,自動匹配所有,則在resultMap中不進行匹配的欄位也可以對映--> <setting name="autoMappingBehavior" value="FULL"/> </settings> <!--指向包含實體類的包--> <typeAliases> <package name="entity"/> </typeAliases> </configuration>
2、實體類:User.java
package entity; public class User { private int uId; private String uName; private String uPwd; private double account; public User() { } public User(int uId, String uName, String uPwd, double account) { this.uId = uId; this.uName = uName; this.uPwd = uPwd; this.account = account; } @Override public String toString() { return "User{" + "uId=" + uId + ", uName='" + uName + '\'' + ", uPwd='" + uPwd + '\'' + ", account=" + account + '}'; } public int getuId() { return uId; } public void setuId(int uId) { this.uId = uId; } public String getuName() { return uName; } public void setuName(String uName) { this.uName = uName; } public String getuPwd() { return uPwd; } public void setuPwd(String uPwd) { this.uPwd = uPwd; } public double getAccount() { return account; } public void setAccount(double account) { this.account = account; } }
3、資料訪問層
dao層介面:userDao.java
package dao; import entity.User; import java.util.List; public interface UserDao { List<User> getAllUser(); }
mapper對映檔案:userMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="dao.UserDao"> <select id="getAllUser" resultType="entity.User"> select * from user </select> </mapper>
4、服務層
服務層介面:userService.java
package service; public interface UserService { void demo(); }
服務層實現類:userServiceImpl.java
package service; import dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service("userService") public class UserServiceImpl implements UserService { @Autowired @Qualifier("userDao") private UserDao userDao; @Override public void demo() { // TODO Auto-generated method stub System.out.println(userDao.getAllUser()); } }
5、測試
junit測試:test.java
import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import service.UserService; public class test { @Test public void testDemo(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.cfg.xml"); UserService service = (UserService)context.getBean("userService"); service.demo(); } }
測試結果: