利用Maven来管理项目中的JAR包,同时使用Spring在业务处理层进行事务管理。数据库使用MySq,数据处理层使用Spring和Mybatis结合。
本案例代码主要结构如图:
1.数据库脚本
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` varchar(20) NOT NULL,
`name` varchar(20) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312; -- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('001', '方舟子');
INSERT INTO `user` VALUES ('002', '小红');
INSERT INTO `user` VALUES ('003', '樱木滑到');
INSERT INTO `user` VALUES ('005', '桃木');
INSERT INTO `user` VALUES ('1', '张三');
INSERT INTO `user` VALUES ('2', '李四');
2.maven配置文件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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hskj</groupId>
<artifactId>maven_spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- JUnit testing framework -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.6.RELEASE</version>
</dependency>
<!-- Spring AOP dependency -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<!-- MySQL database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</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.1</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
</dependencies>
</project>
3.数据库配置文件config.properties
db.driverClass=org.gjt.mm.mysql.Driver
db.jdbcUrl=jdbc:mysql://localhost:3306/test
db.user=root
db.password=root
#
db.initialPoolSize=20
db.maxIdleTime=60
db.maxPoolSize=200
db.minPoolSize=50
#
db.acquireIncrement=3
db.acquireRetryDelay=1000
db.acquireRetryAttempts=30
db.breakAfterAcquireFailure=false
4.Spring配置文件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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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 http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 加载配置文件 -->
<context:property-placeholder location="config.properties" />
<!-- 指定spring注解注入层 -->
<context:component-scan base-package="com.hskj" />
<!-- 数据库连接池管理 -->
<bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${db.driverClass}"></property>
<property name="jdbcUrl" value="${db.jdbcUrl}"></property>
<property name="user" value="${db.user}"></property>
<property name="password" value="${db.password}"></property> <property name="initialPoolSize" value="${db.initialPoolSize}"></property> <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="${db.maxIdleTime}"></property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="${db.maxPoolSize}"></property>
<property name="minPoolSize" value="${db.minPoolSize}"></property> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="${db.acquireIncrement}"></property>
<!--两次连接中间隔时间,单位毫秒。Default: 1000 -->
<property name="acquireRetryDelay" value="${db.acquireRetryDelay}"></property>
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}"></property>
<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
<property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}"></property>
</bean> <!-- ================================事务相关控制================================================= --> <bean name="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="c3p0DataSource"></property>
</bean> <tx:advice id="userTxAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException" />
<tx:method name="insert*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.RuntimeException" />
<tx:method name="update*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="select*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice> <aop:config>
<aop:pointcut id="pc"
expression="execution(public * com.hskj.service.*.*(..))" /> <!--把事务控制在Service层 -->
<aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />
</aop:config> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="c3p0DataSource" />
<property name="configLocation" value="MyBatis-Configuration.xml" />
</bean> <bean class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.hskj.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean> </beans>
5.MyBatis配置文件MyBatis-Configuration.xml、UserDaoMapper.xml
(1)MyBatis-Configuration.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>
<mappers>
<mapper resource="UserDaoMapper.xml"/>
</mappers>
</configuration> (2)UserDaoMapper.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.hskj.mapper.UserMapper"> <parameterMap type="com.hskj.domain.User" id="parameterMapUser">
<parameter property="id"/>
<parameter property="name"/>
</parameterMap> <resultMap type="com.hskj.domain.User" id="resultMapUser">
<result property="id" column="id"/>
<result property="name" column="name"/>
</resultMap> <insert id="insertUser" parameterMap="parameterMapUser">
INSERT INTO user(id,name)
VALUES(?,?)
</insert>
<select id="countAll" resultType="int">
select count(*) c from user;
</select>
<select id="getAllUser" resultMap="resultMapUser">
SELECT * FROM user
</select>
<select id="getById" parameterType="String" resultMap="resultMapUser">
SELECT * FROM user
WHERE id=#{value}
</select>
<delete id="deleteUser" parameterType="String">
DELETE FROM user
WHERE id=#{value}
</delete>
<update id="updateUser" parameterType="java.util.Map">
UPDATE user
SET name=#{name}
WHERE id=#{id}
</update>
</mapper>
下面是JAVA源码部分Spring使用的是注解注入
6.UserMapper类
package com.hskj.mapper; import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.hskj.domain.User; @Service("userMapper")
public interface UserMapper {
public int countAll();
public void insertUser(User user);
public List<User> getAllUser();
public User getById(String id);
public void deleteUser(String id);
public void updateUser(Map<String,Object> map);
}
7.UserDao类
package com.hskj.dao; import java.util.List;
import java.util.Map; import com.hskj.domain.User; public interface UserDao {
public int countAll();
public void insertUser(User user);
public List<User> getAllUser();
public User getById(String id);
public void deleteUser(String id);
public void updateUser(Map<String,Object> map); }
8.UserDaoImpl类
package com.hskj.daoImpl; import java.util.List;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.hskj.dao.UserDao;
import com.hskj.domain.User;
import com.hskj.mapper.UserMapper; @Service("userDao")
public class UserDaoImpl implements UserDao{
@Autowired
private UserMapper userMapper; public int countAll() {
return this.userMapper.countAll();
} @Override
public void insertUser(User user) {
this.userMapper.insertUser(user); } @Override
public List<User> getAllUser() {
return this.userMapper.getAllUser();
} @Override
public User getById(String id) {
return this.userMapper.getById(id);
} @Override
public void deleteUser(String id) {
this.userMapper.deleteUser(id); } @Override
public void updateUser(Map<String, Object> map) {
this.userMapper.updateUser(map);
} }
9.UserService类
package com.hskj.service; import java.util.Map; import com.hskj.domain.User; public interface UserService {
public int countAll();
public void insertUser(User user);
public void update_insert(Map map,User user); }
10.UserServiceImpl类
package com.hskj.serviceImpl; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.hskj.dao.UserDao;
import com.hskj.domain.User;
import com.hskj.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao; public int countAll() {
return this.userDao.countAll();
} @Override
public void insertUser(User user) {
this.userDao.insertUser(user);
throw new RuntimeException("Error");
} @Override
public void update_insert(Map map,User user) {
this.userDao.updateUser(map);
this.userDao.insertUser(user);
throw new RuntimeException("Error"); } }
11.User类
package com.hskj.domain; public class User {
private String id;
private String name; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public User() { } public User(String id, String name) {
super();
this.id = id;
this.name = name;
}
}
12.UserServiceTest类
import java.util.HashMap;
import java.util.Map; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.hskj.domain.User;
import com.hskj.service.UserService; public class UserServiceTest { @Test
public void userServiceTest(){
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService)context.getBean("userService");
User user =new User();
user.setId("003");
user.setName("樱木花道"); Map map=new HashMap();
map.put("id", "001");
map.put("name", "方舟子");
try {
System.out.println(userService.countAll());
//userService.update_insert(map, user);
// userService.insertUser(user);//
} catch (Exception e) {
e.printStackTrace();
} }
}
源代码下载地址:http://pan.baidu.com/s/1ntHgGul