在前面的教學文章中,前面講到有關 mybatis 連線資料庫,然後進行進行資料增刪改查,以及多表聯合查詢的例子,但很多的專案中,通常會用 spring 這個黏合劑來管理 datasource 等。充分利用 spring 基於介面的程式設計,以及aop ,ioc 帶來的方便。用 spring 來管理 mybatis 與管理 hibernate 有很多類似的地方。在這一節中,我們重點介紹資料源管理以及 bean 的組態。
整個Mybatis與Spring整合範例要完成的步驟如下:
1、範例功能描述
2、建立工程
3、資料庫表結構及資料記錄
4、範例物件
5、組態檔案
6、測試執行,輸出結果
在本範例中,需要完成這樣的一個簡單功能,即,指定一個使用者(ID=1),查詢出這個使用者的基本資訊,並關聯查詢這個使用者的所有訂單。
首先建立一個工程的名稱為:mybatis07-spring,在 src 原始碼目錄下建立檔案夾 config,並將原來的 mybatis 組態檔案 Configuration.xml 移動到這個檔案夾中, 並在 config 文家夾中建立 Spring 組態檔案:applicationContext.xml。工程結構目錄如下:
在本範例中,用到兩個表:使用者表和訂單表,其結構和資料記錄如下:
CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(64) NOT NULL DEFAULT '', `mobile` varchar(16) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'yiibai', '13838009988'); INSERT INTO `user` VALUES ('2', 'saya', '13838009988');訂單表結構和資料如下:
CREATE TABLE `order` ( `order_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL DEFAULT '0', `order_no` varchar(16) NOT NULL DEFAULT '', `money` float(10,2) unsigned DEFAULT '0.00', PRIMARY KEY (`order_id`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of order -- ---------------------------- INSERT INTO `order` VALUES ('1', '1', '1509289090', '99.90'); INSERT INTO `order` VALUES ('2', '1', '1519289091', '290.80'); INSERT INTO `order` VALUES ('3', '1', '1509294321', '919.90'); INSERT INTO `order` VALUES ('4', '1', '1601232190', '329.90'); INSERT INTO `order` VALUES ('5', '1', '1503457384', '321.00'); INSERT INTO `order` VALUES ('6', '1', '1598572382', '342.00'); INSERT INTO `order` VALUES ('7', '1', '1500845727', '458.00'); INSERT INTO `order` VALUES ('8', '1', '1508458923', '1200.00'); INSERT INTO `order` VALUES ('9', '1', '1504538293', '2109.00'); INSERT INTO `order` VALUES ('10', '1', '1932428723', '5888.00'); INSERT INTO `order` VALUES ('11', '1', '2390423712', '3219.00'); INSERT INTO `order` VALUES ('12', '1', '4587923992', '123.00'); INSERT INTO `order` VALUES ('13', '1', '4095378812', '421.00'); INSERT INTO `order` VALUES ('14', '1', '9423890127', '678.00'); INSERT INTO `order` VALUES ('15', '1', '7859213249', '7689.00'); INSERT INTO `order` VALUES ('16', '1', '4598450230', '909.20');
使用者表和訂單表分別對應兩個範例物件,分別是:User.java 和 Order.java,它們都在 com.yiibai.pojo 包中。
User.java程式碼內容如下:
package com.yiibai.pojo; import java.util.List; /** * @describe: User * @author: Yiibai * @version: V1.0 * @copyright https://www.tw511.com */ public class User { private int id; private String username; private String mobile; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } }
Order.java程式碼內容如下:
package com.yiibai.pojo; /** * @describe: Order - 訂單 * @author: Yiibai * @version: V1.0 * @copyright https://www.tw511.com */ public class Order { private int orderId; private String orderNo; private float money; private int userId; private User user; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public float getMoney() { return money; } public void setMoney(float money) { this.money = money; } }
這個範例中有三個重要的組態檔案,它們分別是:applicationContext.xml , Configuration.xml 以及 UserMaper.xml。
applicationContext.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> <typeAliases> <typeAlias alias="User" type="com.yiibai.pojo.User" /> <typeAlias alias="Order" type="com.yiibai.pojo.Order" /> </typeAliases> <!-- Mybatis和Spring 整合之後,這些可以完全刪除(注釋掉),資料庫連線的管理交給 Spring 來管理 --> <!-- <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/yiibai?characterEncoding=utf8" /> <property name="username" value="root"/> <property name="password" value=""/> </dataSource> </environment> </environments> --> <mappers> <mapper resource="com/yiibai/maper/UserMaper.xml" /> </mappers> </configuration>
組態檔案 Configuration.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" default-autowire="byName" default-lazy-init="false"> <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/yiibai?characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--dataSource屬性指定要用到的連線池--> <property name="dataSource" ref="dataSource" /> <!--configLocation屬性指定mybatis的核心組態檔案--> <property name="configLocation" value="config/Configuration.xml" /> </bean> <bean id="userMaper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <!--sqlSessionFactory屬性指定要用到的SqlSessionFactory範例--> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> <!--mapperInterface屬性指定對映器介面,用於實現此介面並生成對映器物件--> <property name="mapperInterface" value="com.yiibai.maper.UserMaper" /> </bean> </beans>
UserMaper.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="com.yiibai.maper.UserMaper"> <!-- 為了返回list 型別而定義的returnMap --> <resultMap type="User" id="resultUser"> <id column="id" property="id" /> <result column="username" property="username" /> <result column="mobile" property="mobile" /> </resultMap> <!-- User 聯合 Order 查詢 方法的組態 (多對一的方式) --> <resultMap id="resultUserOrders" type="Order"> <id property="orderId" column="order_id" /> <result property="orderNo" column="order_no" /> <result property="money" column="money" /> <result property="userId" column="user_id" /> <association property="user" javaType="User"> <id property="id" column="id" /> <result property="username" column="username" /> <result property="mobile" column="mobile" /> </association> </resultMap> <select id="getUserOrders" parameterType="int" resultMap="resultUserOrders"> SELECT u.*,o.* FROM `user` u, `order` o WHERE u.id=o.user_id AND u.id=#{id} </select> <select id="getUserById" resultMap="resultUser" parameterType="int"> SELECT * FROM user WHERE id=#{id} </select> </mapper>
我們建立一個測試類為:Main.java , 就在 src 目錄中。其程式碼如下:
import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yiibai.maper.UserMaper; import com.yiibai.pojo.Order; import com.yiibai.pojo.User; /** * Description * @author yiibai * @date 2015-4-12 * @copyright https://www.tw511.com * @email [email protected] * @version 1.0 */ public class Main { private static ApplicationContext ctx; static { ctx = new ClassPathXmlApplicationContext( "config/applicationContext.xml"); } public static void main(String[] args) { UserMaper userMaper = (UserMaper) ctx.getBean("userMaper"); // 測試id=1的使用者查詢,可根據資料庫中的情況修改. User user = userMaper.getUserById(1); System.out.println("獲取使用者 ID=1 的使用者名:"+user.getUsername()); // 得到文章列表測試 System.out.println("得到使用者id為1的所有訂單列表:"); System.out.println("============================================="); List<Order> orders = userMaper.getUserOrders(1); for (Order order : orders) { System.out.println("訂單號:"+order.getOrderNo() + ",訂單金額:" + order.getMoney()); } } }
執行結果如下:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext). log4j:WARN Please initialize the log4j system properly. 獲取使用者 ID=1 的使用者名:yiibai 得到使用者id為1的所有訂單列表: ============================================= 訂單號:1509289090,訂單金額:99.9 訂單號:1519289091,訂單金額:290.8 訂單號:1509294321,訂單金額:919.9 訂單號:1601232190,訂單金額:329.9 訂單號:1503457384,訂單金額:321.0 訂單號:1598572382,訂單金額:342.0 訂單號:1500845727,訂單金額:458.0 訂單號:1508458923,訂單金額:1200.0 訂單號:1504538293,訂單金額:2109.0 訂單號:1932428723,訂單金額:5888.0 訂單號:2390423712,訂單金額:3219.0 訂單號:4587923992,訂單金額:123.0 訂單號:4095378812,訂單金額:421.0 訂單號:9423890127,訂單金額:678.0 訂單號:7859213249,訂單金額:7689.0 訂單號:4598450230,訂單金額:909.2
程式碼下載:Mybatis與Spring整合