Spring + SpringMVC整合MyBatis
阿新 • • 發佈:2018-12-09
在上一篇文章IDEA使用maven搭建Spring + SpringMVC環境的基礎上,我們再將MyBatis框架整合進去,這樣就可以搭建一個完整的SSM環境了。
1.在pom.xml中新增mysql,jdcb,mybatis依賴並匯入依賴,所有依賴如下:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <springVersion>4.2.6.RELEASE</springVersion> <mysqlVersion>5.1.38</mysqlVersion> <c3p0Version>0.9.1.2</c3p0Version> <myBatisVersion>3.4.1</myBatisVersion> </properties> <dependencies> <!--spring框架的基礎包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springVersion}</version> </dependency> <!--springMVC的兩個包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springVersion}</version> </dependency> <!--jdbc依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${springVersion}</version> </dependency> <!--mysql依賴--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysqlVersion}</version> <scope>runtime</scope> </dependency> <!--myBaits依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${myBatisVersion}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!--連線池--> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${c3p0Version}</version> </dependency> <!--junit包--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--測試依賴包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${springVersion}</version> <scope>test</scope> </dependency> </dependencies>
2.在資料庫中新增Book資料表,並填充資料,sql語句如下:
DROP TABLE IF EXISTS `book`; CREATE TABLE `book` ( `book_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '圖書ID', `name` varchar(100) NOT NULL COMMENT '圖書名稱', `number` int(11) NOT NULL COMMENT '館藏數量', PRIMARY KEY (`book_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1004 DEFAULT CHARSET=utf8 COMMENT='圖書表'; # # Data for table "book" # INSERT INTO `book` VALUES (1000,'Java程式設計',9),(1001,'資料結構',7),(1002,'設計模式',7),(1003,'編譯原理',9);
3.建立pojo資料夾並新建Book.java類
package pojo; /** * Created By Seven.wk * Description: Book物件 * Created At 2018/09/13 */ public class Book { private int bookId;// 圖書ID private String name;// 圖書名稱 private int number;// 館藏數量 public Book() { } public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } @Override public String toString() { return "Book{" + "bookId=" + bookId + ", name='" + name + '\'' + ", number=" + number + '}'; } }
4.建立dao層資料夾並建立dao層介面
package dao;
import org.apache.ibatis.annotations.Param;
import pojo.Book;
import java.util.List;
/**
* Created By Seven.wk
* Description: dao層介面
* Created At 2018/09/13
*/
public interface BookMapper {
/**
* 通過ID查詢單本圖書
*
* @param bookId
* @return
*/
Book queryById(int bookId);
/**
* 查詢所有圖書
*
* @param offset 查詢起始位置
* @param limit 查詢條數
* @return
*/
List<Book> queryAll(@Param("offset") int offset, @Param("limit") int limit);
/**
* 減少館藏數量
*
* @param bookId
* @return 如果影響行數等於>1,表示更新的記錄行數
*/
int reduceNumber(int bookId);
}
5.在resources資料夾下新建mappers資料夾並存放dao層對映檔案
6.新建BookMapper.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="dao.BookMapper">
<resultMap id="BaseResultMap" type="pojo.Book">
<id column="book_id" property="bookId" jdbcType="BIGINT"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="number" property="number" jdbcType="INTEGER"/>
</resultMap>
<sql id="Base_Column_List">
book_id, name, number
</sql>
<select id="queryById" parameterType="INTEGER" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from book
where book_id = #{id}
</select>
<select id="queryAll" parameterType="Map" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from book
limit #{limit}
offset #{offset}
</select>
<update id="reduceNumber" parameterType="INTEGER">
update book
set number = number - 1
where
book_id = #{bookId}
</update>
</mapper>
7.在resources資料夾下新建jdbc資料夾,存放jdbc.properties作為資料庫的配置檔案
jdbc.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/servlet?useUnicode=true&characterEncoding=utf8
jdbc.username = root
jdbc.password = root
8.在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:context="http://www.springframework.org/schema/context"
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">
<!--掃描service資料夾下的包-->
<context:component-scan base-package="service"/>
<!--載入jdbc的配置檔案-->
<context:property-placeholder location="classpath:jdbc/jdbc.properties"/>
<!--配置資料庫連線池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--連線池屬性-->
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--c3p0連線池的私有屬性-->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!--連線關閉後不自動commit-->
<property name="autoCommitOnClose" value="false"/>
<!--連線超時時間-->
<property name="checkoutTimeout" value="10000"/>
<!--連線失敗重試次數-->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--配置SqlSessionFactory物件-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入資料庫連線池-->
<property name="dataSource" ref="dataSource"/>
<!--掃描實體包-->
<property name="typeAliasesPackage" value="pojo"/>
<!--掃描sql配置檔案:mapper需要的xml檔案-->
<property name="mapperLocations" value="classpath:mappers/*.xml"/>
</bean>
<!--配置掃描Dao介面包,動態實現Dao介面,注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入到sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--需要掃描Dao介面包-->
<property name="basePackage" value="dao"/>
</bean>
<!--配置事務管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入資料庫連線池-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
至此,前面沒有問題的話,一個ssm環境就簡單的整合完成了!下面我們搭建測試環境測試dao層介面
9.在pom.xml引入測試的依賴
<!--測試依賴包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springVersion}</version>
<scope>test</scope>
</dependency>
10.新建BookMapper.java 的測試類BookMapperTest.java,並新增上下文,程式碼如下:
package dao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import pojo.Book;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/applicationContext.xml"})
public class BookMapperTest {
@Autowired
private BookMapper bookMapper;
@Test
public void queryById() {
int id = 1003;
Book book = bookMapper.queryById(id);
System.out.println(book.toString());
}
@Test
public void queryAll() {
List<Book> bookList = bookMapper.queryAll(1, 3);
for(Book book : bookList)
System.out.println(book);
}
@Test
public void reduceNumber() {
int result = bookMapper.reduceNumber(1000);
System.out.println(result);
}
}
11.進行測試,測試通過,則環境整合完成!
12.專案整體的目錄結構如下: