Spring3.x集成MyBatis3

  1.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>com.tliu</groupId>
	<artifactId>case</artifactId>
	<packaging>war</packaging>
	<version>1.1-SNAPSHOT</version>
	<name>case</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>3.2.10.RELEASE</spring.version>
	</properties>	

	<!-- 构件发布到Nexus仓库 -->
	<distributionManagement>
		<repository>
		     <id>nexus-releases</id>
		     <url>http://192.168.2.2:8081/nexus/content/repositories/releases/</url>
		</repository>
		<snapshotRepository>
		     <id>nexus-snapshots</id>
		     <url>http://192.168.2.2:8081/nexus/content/repositories/snapshots/</url>
		</snapshotRepository>
	</distributionManagement>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>
		<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-context-support</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-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>0.2.25</version>
		</dependency>
		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.0.1</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.8</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.26</version>
		</dependency>
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>10.2.0.3.0</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.4</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.7.1</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.1</version>
		</dependency>
		<dependency>
			<groupId>com.kenai.nbpwr</groupId>
			<artifactId>javax-inject</artifactId>
			<version>1.0-201002241208</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.3</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.5.0</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.20</version>
		</dependency>
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>6.0-RC2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<!-- 编译插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<!-- 资源管理插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- 测试插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.7.2</version>
				<configuration>
					<forkMode>once</forkMode>
					<argLine>-Dfile.encoding=UTF-8</argLine>
				</configuration>
			</plugin>
			<!-- 生成API文档插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.9.1</version>
				<configuration>
					<show>private</show>
					<nohelp>true</nohelp>
					<encoding>utf-8</encoding>
				</configuration>
				<executions>
					<execution>
						<id>attach-javadocs</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<!-- 打包源代码插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.2.1</version>
				<executions>
					<execution>
						<id>attach-sources</id>
						<phase>verify</phase>
						<goals>
							<goal>jar-no-fork</goal>
						</goals>
					</execution>
				</executions>
			</plugin>			
		</plugins>
		<!-- 打包时包含.xml文件和.properties文件,maven默认情况不包含 -->
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.xml</include>
					<include>**/*.properties</include>
				</includes>
			</resource>
		</resources>
	</build>

</project>

  2.Spring主配置文件

<?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"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd">

	<!--读取外部的属性文件配置参数 -->
	<context:property-placeholder location="classpath:conf.properties" />
	
	<context:component-scan base-package="com.tliu.case2">
		<context:exclude-filter type="regex" expression="com.tliu.case2.web.*"/>
	</context:component-scan>
	
	<context:annotation-config/>	
	
	<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- 数据库基本信息配置 -->
		<property name="driverClassName" value="${oracle.driver}" />
		<property name="url" value="${oracle.url}" />
		<property name="username" value="${oracle.username}" />
		<property name="password" value="${oracle.password}" />		
		<!-- 初始化连接数量 -->
		<property name="initialSize" value="${druid.initialSize}" />
		<!-- 最大并发连接数 -->
		<property name="maxActive" value="${druid.maxActive}" />
		<!-- 最大空闲连接数 -->
		<property name="maxIdle" value="${druid.maxIdle}" />
		<!-- 最小空闲连接数 -->
		<property name="minIdle" value="${druid.minIdle}" />
		<!-- 配置获取连接等待超时的时间 -->		
		<property name="maxWait" value="${druid.maxWait}" />
		<!-- 超过时间限制是否回收 -->
		<property name="removeAbandoned" value="${druid.removeAbandoned}" />
		<!-- 超过时间限制多长; -->
		<property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}" />
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
		<!-- 用来检测连接是否有效的sql,要求是一个查询语句-->	
		<property name="validationQuery" value="${druid.validationQuery}" />
		<!-- 申请连接的时候检测 -->
		<property name="testWhileIdle" value="${druid.testWhileIdle}" />
		<!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 -->
		<property name="testOnBorrow" value="${druid.testOnBorrow}" />
		<!-- 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能  -->
		<property name="testOnReturn" value="${druid.testOnReturn}" />
		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
		<property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />		
		<property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}" />
		<!--属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:  				
				监控统计用的filter:stat
				日志用的filter:log4j
 				防御SQL注入的filter:wall -->
		<property name="filters" value="${druid.filters}" />		
	</bean>	
	
	<!-- 会话工厂-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="druidDataSource" />
		<property name="mapperLocations" value="classpath:com/tliu/case2/domain/*Mapper.xml" />
		<property name="typeAliasesPackage" value="com.tliu.case2.domain" />
	</bean>
	
	<!-- Mapper接口类自动装配 注 意 , 没 有 必 要 去 指 定 SqlSessionFactory 或 SqlSessionTemplate , 
	因 为 MapperScannerConfigurer 将会创建 MapperFactoryBean,之后自动装配。但是,如果你使 用了一个 以上的 DataSource ,那 么自动 装配可 能会失效 。这种 情况下 ,
	你可 以使用 sqlSessionFactoryBeanName 或 sqlSessionTemplateBeanName 属性来设置正确的 bean 名 称来使用。这就是它如何来配置的,注意 bean 的名称是必须的,而不是 bean 的引用,因 此,value 属性在这里替代通常的 ref:
	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	-->
	<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="annotationClass" value="org.springframework.stereotype.Repository"/>
		<property name="basePackage" value="com.tliu.case2.mapper" />
	</bean>	
	
	<!-- 事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="druidDataSource" />
	</bean>
	
	<!-- 声明式事务 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" rollback-for="RuntimeException" />
			<tx:method name="remove*" propagation="REQUIRED" rollback-for="RuntimeException" />				
			<tx:method name="update*" propagation="REQUIRED" rollback-for="RuntimeException" />				
			<tx:method name="init*" propagation="REQUIRED" rollback-for="RuntimeException" />
			<tx:method name="select*" propagation="SUPPORTS" />
			<tx:method name="find*" propagation="SUPPORTS" />
			<tx:method name="get*" propagation="SUPPORTS" />
			<tx:method name="*" propagation="REQUIRED" rollback-for="RuntimeException" />				
		</tx:attributes>
	</tx:advice>
	
	<!-- 事务通知 -->
	<aop:config>
		<aop:pointcut expression="execution(* com.tliu.case2.service..*.*(..))" id="pointCut" />			
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut" />
	</aop:config>
	
</beans>

 3.conf.properties 

druid.initialSize = 5
druid.maxActive = 10
druid.maxIdle = 6
druid.minIdle = 3
druid.maxWait = 60000
druid.removeAbandoned = true
druid.removeAbandonedTimeout = 180
druid.timeBetweenEvictionRunsMillis = 60000
druid.minEvictableIdleTimeMillis = 300000
druid.validationQuery = SELECT 1 FROM DUAL
druid.testWhileIdle = true 
druid.testOnBorrow = false
druid.testOnReturn = false
druid.poolPreparedStatements = true
druid.maxPoolPreparedStatementPerConnectionSize = 50
druid.filters = stat

 4.实体类 

package com.tliu.case2.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable{
	
	private static final long serialVersionUID = 4714695050355640732L;

	private String userid;
	
	private String username;
	
	private String nickname;
	
	private String password;
	
	private Date createDate = new Date();
	
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}	

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getUserid() {
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	@Override
	public String toString() {
		return "User [userid=" + userid + ", username=" + username
				+ ", nickname=" + nickname + ", password=" + password
				+ ", createDate=" + createDate + "]";
	}
	
	
}

  5.UserMapper接口 & UserMapper.xml

package com.tliu.case2.mapper;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.tliu.case2.domain.User;

@Repository
public interface UserMapper {

	int addUser(User user);	
	
	List<User> findList();
}
<?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.tliu.case2.mapper.UserMapper">
	<resultMap type="User" id="userMap">
		<result column="ID" property="userid"/>
		<result column="USER_NAME" property="username"/>
		<result column="NICK_NAME" property="nickname"/>
		<result column="PASSWORD" property="password"/>
		<result column="CREATE_DATE" property="createDate"/>
	</resultMap>
	
    <insert id="addUser" parameterType="User">
        <![CDATA[
        	INSERT INTO SYS_USER(ID,
        	                     USER_NAME,
        	                     NICK_NAME,
        	                     PASSWORD,
        	                     CREATE_DATE)
                   VALUES(#{userid},
                          #{username},
                          #{nickname},
                          #{password},
                          #{createDate})
        ]]>
    </insert>
    <select id="findList" resultMap="userMap">
    	<![CDATA[
    		SELECT * FROM SYS_USER
    	]]>
    </select>
    
</mapper>

  6.UserService & UserServiceImpl 

package com.tliu.case2.service;

import java.util.List;

import com.tliu.case2.domain.User;

public interface UserService {
	
	int addUser(User user);
	
	List<User> findList();
}

 

package com.tliu.case2.service.impl;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.tliu.case2.domain.User;
import com.tliu.case2.mapper.UserMapper;
import com.tliu.case2.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService{

	@Inject
	private UserMapper userMapper;
	
	public int addUser(User user) {			
		return userMapper.addUser(user);
	}

	@Override
	public List<User> findList() {
		return userMapper.findList();
	}

}

 7.编写测试代码 

package com.tliu.case2.service;

import java.util.List;
import java.util.UUID;

import javax.inject.Inject;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.tliu.case2.domain.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/beans.xml")
public class MainTest {
	
	@Inject
	private UserService userService;
	
	@Test
	public void init(){
		Assert.assertNotNull(userService);
	}
	
	@Test
	public void testAdd(){
		User user = new User();
		user.setNickname("Jack");
		user.setPassword("123456");
		user.setUsername("Jack-OK");
		user.setUserid(UUID.randomUUID().toString());
		userService.addUser(user);
	}

	@Test
	public void testFindUsers(){
		List<User> users = userService.findList();
		Assert.assertNotNull(users);
	}
}


你可能感兴趣的:(Spring3.x集成MyBatis3)