位置:首頁 > Java技術 > MyBatis教學 > Mybatis與Spring集成

Mybatis與Spring集成

在前麵的教學文章中,前麵講到有關 mybatis 連接數據庫,然後進行進行數據增刪改查,以及多表聯合查詢的例子,但很多的項目中,通常會用 spring 這個粘合劑來管理 datasource 等。充分利用 spring 基於接口的編程,以及aop ,ioc 帶來的方便。用 spring 來管理 mybatis 與管理 hibernate 有很多類似的地方。在這一節中,我們重點介紹數據源管理以及 bean 的配置。

整個Mybatis與Spring集成示例要完成的步驟如下:

1、示例功能描述

2、創建工程

3、數據庫表結構及數據記錄

4、實例對象

5、配置文件

6、測試執行,輸出結果

1、示例功能描述

在本示例中,需要完成這樣的一個簡單功能,即,指定一個用戶(ID=1),查詢出這個用戶的基本信息,並關聯查詢這個用戶的所有訂單。

2、創建工程

 首先創建一個工程的名稱為:mybatis07-spring,在 src 源代碼目錄下建立文件夾 config,並將原來的 mybatis 配置文件 Configuration.xml 移動到這個文件夾中, 並在 config 文家夾中建立 Spring 配置文件:applicationContext.xml。工程結構目錄如下:

Mybatis與Spring集成

3、數據庫表結構及數據記錄

在本示例中,用到兩個表:用戶表和訂單表,其結構和數據記錄如下:

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');

4、實例對象

用戶表和訂單表分彆對應兩個實例對象,分彆是: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 http://www.gitbook.net
 */  
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 http://www.gitbook.net
 */
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;
	}

}

5、配置文件

這個實例中有三個重要的配置文件,它們分彆是: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>

6、測試執行,輸出結果

我們創建一個測試類為: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 http://www.gitbook.net
 * @email gitbook.net@gmai.com
 * @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集成