MyBatis(8)——Mybatis3.x與Spring4.x整合
阿新 • • 發佈:2019-02-13
sql
CREATE DATABASE spring4_mybatis3; USE spring4_mybatis3; DROP TABLE IF EXISTS t_user; CREATE TABLE t_user ( user_id CHAR(32) NOT NULL, user_name VARCHAR(30) DEFAULT NULL, user_birthday DATE DEFAULT NULL, user_salary DOUBLE DEFAULT NULL, PRIMARY KEY (user_id) ) ENGINE=INNODB DEFAULT CHARSET=utf8;
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>me</groupId> <artifactId>spring4-mybatis3</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring4-mybatis3 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- 新增Spring-core包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 新增spring-context包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 新增spring-tx包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 新增spring-jdbc包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 為了方便進行單元測試,新增spring-test包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!--新增spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!--新增aspectjweaver包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.5</version> </dependency> <!-- 新增mybatis的核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!-- 新增mybatis與Spring整合的核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 新增servlet3.0核心包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.2-b01</version> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 新增mysql驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <!-- 新增druid連線池包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.12</version> </dependency> <!-- 新增junit單元測試包 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>spring4-mybatis3</finalName> </build> </project>
dbconfig.properties
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/spring4_mybatis3?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=root
spring.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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 引入dbconfig.properties屬性檔案 --> <context:property-placeholder location="classpath:dbconfig.properties" /> <!-- 自動掃描(自動注入),掃描me.gacl.service這個包以及它的子包的所有使用@Service註解標註的類 --> <context:component-scan base-package="me.service" /> </beans>
spring-mybatis.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<!-- JNDI方式配置資料來源 -->
<!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> -->
<!-- ========================================配置資料來源========================================= -->
<!-- 配置資料來源,使用的是alibaba的Druid(德魯伊)資料來源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<!-- 初始化連線大小 -->
<property name="initialSize" value="0" />
<!-- 連線池最大使用連線數量 -->
<property name="maxActive" value="20" />
<!-- 連線池最大空閒 -->
<property name="maxIdle" value="20" />
<!-- 連線池最小空閒 -->
<property name="minIdle" value="0" />
<!-- 獲取連線最大等待時間 -->
<property name="maxWait" value="60000" />
<!--
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="33" />
-->
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一個連線在池中最小生存的時間,單位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 開啟removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分鐘 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 關閉abanded連線時輸出錯誤日誌 -->
<property name="logAbandoned" value="true" />
<!-- 監控資料庫 -->
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat" />
</bean>
<!-- ========================================分隔線========================================= -->
<!-- ========================================針對myBatis的配置項============================== -->
<!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 例項化sqlSessionFactory時需要使用上述配置好的資料來源以及SQL對映檔案 -->
<property name="dataSource" ref="dataSource" />
<!-- 自動掃描me/mapping/目錄下的所有SQL對映的xml檔案, 省掉Configuration.xml裡的手工配置
value="classpath:me/mapping/*.xml"指的是classpath(類路徑)下me.mapping包中的所有xml檔案
UserMapper.xml位於me.mapping包下,這樣UserMapper.xml就可以被自動掃描
-->
<property name="mapperLocations" value="classpath:me/mapping/*.xml" />
</bean>
<!-- 配置掃描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 掃描me.dao這個包以及它的子包下的所有對映介面類 -->
<property name="basePackage" value="me.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- ========================================分隔線========================================= -->
<!-- 配置Spring的事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 註解方式配置事物 -->
<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
<!-- 攔截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="append*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="repair" propagation="REQUIRED" />
<tx:method name="delAndRepair" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" />
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* me.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config>
<!-- 配置druid監控spring jdbc -->
<bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
</bean>
<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
<property name="patterns">
<list>
<value>me.service.*</value>
</list>
</property>
</bean>
<aop:config>
<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
</aop:config>
</beans>
User實體
package me.domain;
import java.util.Date;
public class User {
private String userId;
private String userName;
private Date userBirthday;
private Double userSalary;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId == null ? null : userId.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public Date getUserBirthday() {
return userBirthday;
}
public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
}
public Double getUserSalary() {
return userSalary;
}
public void setUserSalary(Double userSalary) {
this.userSalary = userSalary;
}
}
userMapper.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="me.dao.UserMapper" >
<resultMap id="BaseResultMap" type="me.domain.User" >
<id column="user_id" property="userId" jdbcType="CHAR" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="user_birthday" property="userBirthday" jdbcType="DATE" />
<result column="user_salary" property="userSalary" jdbcType="DOUBLE" />
</resultMap>
<sql id="Base_Column_List" >
user_id, user_name, user_birthday, user_salary
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from t_user
where user_id = #{userId,jdbcType=CHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
delete from t_user
where user_id = #{userId,jdbcType=CHAR}
</delete>
<insert id="insert" parameterType="me.domain.User" >
insert into t_user (user_id, user_name, user_birthday,
user_salary)
values (#{userId,jdbcType=CHAR}, #{userName,jdbcType=VARCHAR}, #{userBirthday,jdbcType=DATE},
#{userSalary,jdbcType=DOUBLE})
</insert>
<insert id="insertSelective" parameterType="me.domain.User" >
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="userId != null" >
user_id,
</if>
<if test="userName != null" >
user_name,
</if>
<if test="userBirthday != null" >
user_birthday,
</if>
<if test="userSalary != null" >
user_salary,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="userId != null" >
#{userId,jdbcType=CHAR},
</if>
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
</if>
<if test="userBirthday != null" >
#{userBirthday,jdbcType=DATE},
</if>
<if test="userSalary != null" >
#{userSalary,jdbcType=DOUBLE},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="me.domain.User" >
update t_user
<set >
<if test="userName != null" >
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="userBirthday != null" >
user_birthday = #{userBirthday,jdbcType=DATE},
</if>
<if test="userSalary != null" >
user_salary = #{userSalary,jdbcType=DOUBLE},
</if>
</set>
where user_id = #{userId,jdbcType=CHAR}
</update>
<update id="updateByPrimaryKey" parameterType="me.domain.User" >
update t_user
set user_name = #{userName,jdbcType=VARCHAR},
user_birthday = #{userBirthday,jdbcType=DATE},
user_salary = #{userSalary,jdbcType=DOUBLE}
where user_id = #{userId,jdbcType=CHAR}
</update>
<!-- ==============以下內容是根據自身業務擴充套件的內容======================= -->
<!-- select標籤的id屬性與UserMapper介面中定義的getAllUser方法要一模一樣 -->
<select id="getAllUser" resultMap="BaseResultMap">
select user_id, user_name, user_birthday, user_salary from t_user
</select>
</mapper>
Dao: UserMapper.java
package me.dao;
import me.domain.User;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(String userId);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(String userId);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
/**獲取所有使用者資訊
* @return List<User>
*/
List<User> getAllUser();
}
service 介面
package me.service;
import java.util.List;
import me.domain.User;
public interface UserServiceI {
/**
* 新增使用者
* @param user
*/
void addUser(User user);
/**
* 根據使用者id獲取使用者
* @param userId
* @return
*/
User getUserById(String userId);
/**獲取所有使用者資訊
* @return List<User>
*/
List<User> getAllUser();
}
service實現類
package me.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import me.dao.UserMapper;
import me.domain.User;
import me.service.UserServiceI;
/**
*
* 使用@Service註解將UserServiceImpl類標註為一個service
* service的id是userService
*/
@Service("userService")
public class UserServiceImpl implements UserServiceI {
/**
* 使用@Autowired註解標註userMapper變數,
* 當需要使用UserMapper時,Spring就會自動注入UserMapper
*/
@Autowired
private UserMapper userMapper;//注入dao
public void addUser(User user) {
userMapper.insert(user);
}
public User getUserById(String userId) {
// TODO Auto-generated method stub
return userMapper.selectByPrimaryKey(userId);
}
/**獲取所有使用者資訊
* @return List<User>
*/
public List<User> getAllUser(){
return userMapper.getAllUser();
}
}
單元測試
package me.test;
import java.util.Date;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import me.domain.User;
import me.service.UserServiceI;
public class MyBatisTest {
private UserServiceI userService;
/**
* 這個before方法在所有的測試方法之前執行,並且只執行一次
* 所有做Junit單元測試時一些初始化工作可以在這個方法裡面進行
* 比如在before方法裡面初始化ApplicationContext和userService
*/
@Before
public void before(){
//使用"spring.xml"和"spring-mybatis.xml"這兩個配置檔案建立Spring上下文
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});
//從Spring容器中根據bean的id取出我們要使用的userService物件
userService = (UserServiceI) ac.getBean("userService");
}
@Test
public void testAddUser(){
//ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});
//UserServiceI userService = (UserServiceI) ac.getBean("userService");
User user = new User();
user.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));
user.setUserName("qww");
user.setUserBirthday(new Date());
user.setUserSalary(10000D);
userService.addUser(user);
}
@Test
public void testfind(){
//ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});
//UserServiceI userService = (UserServiceI) ac.getBean("userService");
User user =userService.getUserById("344e39bd57414e54b488848c7b9c56c8");
System.out.println(user);
}
}
使用Spring提供的Junit測試框架進行單元測試package me.test;
import java.util.Date;
import java.util.UUID;
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 me.domain.User;
import me.service.UserServiceI;
@RunWith(SpringJUnit4ClassRunner.class)
//配置了@@ContextConfiguration註解並使用該註解的locations屬性指明spring配置檔案
@ContextConfiguration(locations={"classpath:spring.xml", "classpath:spring-mybatis.xml" })
public class MyBatisTestBySpringTestFramework {
//注入userService
@Autowired
private UserServiceI userService;
@Test
public void testAddUser(){
User user = new User();
user.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));
user.setUserName("lllc");
user.setUserBirthday(new Date());
user.setUserSalary(10000D);
userService.addUser(user);
}
@Test
public void testGetUserById(){
String userId = "c9927ecad41c43c993a60d4e0a2481e9";
User user = userService.getUserById(userId);
System.out.println(user.getUserName());
}
}
web測試
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<description>Spring監聽器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- ContextLoaderListener初始化Spring上下文時需要使用到的contextConfigLocation引數 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 配置spring.xml和spring-mybatis.xml這兩個配置檔案的位置,固定寫法 -->
<param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
</context-param>
</web-app>
<pre name="code" class="html">UserServlet
package me.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import me.domain.User;
import me.service.UserServiceI;
/**
*
* @WebServlet是Servlet3.0提供的註解,目的是將一個繼承了HttpServlet類的普通java類標註為一個Servlet
* UserServlet使用了@WebServlet標註之後,就不需要在web.xml中配置了
*/
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
//處理業務邏輯的userService
private UserServiceI userService;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//獲取所有的使用者資訊
List<User> lstUsers = userService.getAllUser();
request.setAttribute("lstUsers", lstUsers);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
public void init() throws ServletException {
//在Servlet初始化時獲取Spring上下文物件(ApplicationContext)
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
//從ApplicationContext中獲取userService
userService = (UserServiceI) ac.getBean("userService");
}
}
編輯index.jsp頁面,用於展示查詢到的使用者資訊,內容如下
<%@ page language="java" pageEncoding="UTF-8"%>
<%--引入JSTL核心標籤庫 --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<title>顯示使用者資訊</title>
<style type="text/css">
table,td{
border: 1px solid;
border-collapse: collapse;
}
</style>
</head>
<body>
<table>
<tr>
<td>使用者ID</td>
<td>使用者名稱</td>
<td>使用者生日</td>
<td>工資</td>
</tr>
<%--遍歷lstUsers集合中的User物件 --%>
<c:forEach var="user" items="${lstUsers}">
<tr>
<td>${user.userId}</td>
<td>${user.userName}</td>
<td>${user.userBirthday}</td>
<td>${user.userSalary}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
輸入地址:http://localhost:8080/spring4-mybatis3/UserServlet 訪問UserServlet