Mybatis與Spring整合

AngeliaZheng發表於2018-09-11

在前面的有關Mybatis的文章中,講到有關 mybatis 連線資料庫,然後進行進行資料增刪改查,以及多表聯合查詢的例子,但很多的實際專案中,通常會用 spring 來管理 datasource 等。充分利用 spring 基於介面的程式設計,以及aop,ioc 帶來的方便。在這一節中,我們重點介紹資料來源管理以及 bean 的配置。

應用場景:首先根據文章 ID 讀取一篇文章資訊,然後再讀取這篇文章的評論。
1. 建立 maven 工程

2. pom新增jar依賴

<dependencies>
	<!-- spring需要的jar包依賴 -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-core</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-test</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-tx</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-beans</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-jdbc</artifactId>
		<version>${spring.version}</version>
	</dependency>

	<!-- mybatis的jar包依賴 -->
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
		<version>3.4.4</version>
	</dependency>
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis-spring</artifactId>
		<version>1.3.0</version>
	</dependency>

	<!-- mysql的jar包依賴 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>8.0.12</version>
	</dependency>

	<dependency>
		<groupId>commons-dbcp</groupId>
		<artifactId>commons-dbcp</artifactId>
		<version>1.4</version>
	</dependency>
	<dependency>
		<groupId>commons-pool</groupId>
		<artifactId>commons-pool</artifactId>
		<version>1.6</version>
	</dependency>

	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.11</version>
		<scope>test</scope>
	</dependency>
</dependencies>

3. 準備資料庫表結構及資料記錄

參考前面文章,這裡省略。

4. 建立實體物件

public class Article {
	private int id;
	private String title;
	private String content;
	
	private List<Comment> comments;

	// getters and setters
}

public class Comment {
	private int id;
	private String commentcontent;
	private String postedBy;
	
	private Article article;

	// getters and setters
}

5. 建立介面和MyBatis對映檔案

public interface IArticle {
	public Article getArticleAndComments(int id);	
	public Article getArticleById(int id);
}

public interface IComment {
	public Comment getComment(int cid);
}
<mapper namespace="com.angelia.mybatis.dao.IArticle">
	
	<!-- 為了返回list 型別而定義的returnMap -->
	<resultMap id="articleMap" type="Article" >
		<id column="id" property="id" />
		<!-- <result property="id" column="id" /> -->
		<result property="title" column="title" />
		<result property="content" column="content" />
	</resultMap>
	
	<!-- Article級聯評論查詢 方法配置 (一篇文章對多個評論) -->
	<resultMap id="articleCommentMap" type="Article" extends="articleMap">
		<collection property="comments" ofType="com.angelia.mybatis.model.Comment" column="aid">
			<id property="id" column="cid" javaType="int" jdbcType="INTEGER" />
			<result property="commentcontent" column="commentcontent" javaType="string" jdbcType="VARCHAR" />
			<result property="postedBy" column="postedBy" javaType="string" jdbcType="VARCHAR" />
		</collection>
	</resultMap>
	
	<select id="getArticleAndComments" resultMap="articleCommentMap" parameterType="int">
		SELECT a.*, c.*
		FROM article a, comment c
		WHERE a.id = c.aid AND a.id = #{aid}
	</select>
	
	<select id="getArticleById" resultMap="articleMap" parameterType="int">
		SELECT *
		FROM article
		WHERE id = #{id}
	</select>  

</mapper>

<mapper namespace="com.angelia.mybatis.dao.IComment">

	<resultMap id="commentMap" type="Comment">
		<id property="id" column="cid" />
		<result property="commentcontent" column="commentcontent" />
		<result property="postedBy" column="postedBy" />
	</resultMap>

	<resultMap id="commentArticleMap" type="Comment" extends="commentMap">
		<association property="article" javaType="Article">
			<id property="id" column="aid" />
			<result property="title" column="title" />
			<result property="content" column="content" />
		</association>
	</resultMap>

	<select id="getComment" resultMap="commentArticleMap" parameterType="int">
		SELECT a.*, c.*
		FROM article a, comment c
		WHERE a.id = c.aid AND c.cid = #{cid}
	</select>

</mapper>

6. 建立Spring和MyBatis的配置檔案applicationContext.xml和mybatis-config.xml

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>
	<typeAliases>
		<typeAlias alias="Article" type="com.angelia.mybatis.model.Article" />
		<typeAlias alias="Comment" type="com.angelia.mybatis.model.Comment" />
	</typeAliases>
	<!-- Mybatis和Spring 整合之後,這些可以完全刪除(註釋掉),資料庫連線的管理交給 Spring 來管理 -->
	<!-- <environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments> -->
	<mappers>
		<mapper resource="Article.xml" />
		<mapper resource="Comment.xml" />
	</mappers>
</configuration>

applicationContext.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.cj.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/hibernatetest?useSSL=false&amp;serverTimezone=UTC" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!--dataSource屬性指定要用到的連線池 -->
		<property name="dataSource" ref="dataSource" />
		<!--configLocation屬性指定mybatis的核心配置檔案 -->
		<property name="configLocation" value="mybatis-config.xml" />
	</bean>

	<bean id="articleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<!--sqlSessionFactory屬性指定要用到的SqlSessionFactory例項 -->
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
		<!--mapperInterface屬性指定對映器介面,用於實現此介面並生成對映器物件 -->
		<property name="mapperInterface" value="com.angelia.mybatis.dao.IArticle" />
	</bean>
</beans>

7. 建立測試類

public class MyBatisSpringTest {
	private static ApplicationContext ctx;
	static{
		ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	
	@Test
	public void test() {
		IArticle articleMapper = (IArticle) ctx.getBean("articleMapper");
		// 測試id=1的使用者查詢,可根據資料庫中的情況修改.
		Article article = articleMapper.getArticleAndComments(1);
		System.out.println(article);

		Article article2 = articleMapper.getArticleById(1);
		System.out.println(article2);
	}
}

 

相關文章