Spring+Mybatis+MySql+Maven 简单的事务管理案例
利用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
Spring+Mybatis+MySql+Maven 简单的事务管理案例的更多相关文章
- freemarker + spring mvc + spring + mybatis + mysql + maven项目搭建
今天说说搭建项目,使用freemarker + spring mvc + spring + mybatis + mysql + maven搭建web项目. 先假设您已经配置好eclipse的maven ...
- dubbo+zookeeper+jsp+springmvc+spring+mybatis+mysql+maven完整示例
项目分为三部分,这里分为三个maven项目(基于web,所以最后一个为maven创建的web项目) 1.接口定义以及实体类定义(api+pojo) --- maven创建java项目,打包成jar 2 ...
- springmvc学习总结(二) -- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解
@_@ 写在最前 之前分享过下面这几篇: mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)(附demo和搭建过程遇到的问题解决方法) myba ...
- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解
转自:https://www.cnblogs.com/lmei/p/7190755.html?utm_source=itdadao&utm_medium=referral @_@ 写在最前 之 ...
- 利用Intellij+MAVEN搭建Spring+Mybatis+MySql+SpringMVC项目详解
http://blog.csdn.net/noaman_wgs/article/details/53893948 利用Intellij+MAVEN搭建Spring+Mybatis+MySql+Spri ...
- Spring+Mybatis+SpringMVC+Maven+MySql搭建实例
林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文主要讲了如何使用Maven来搭建Spring+Mybatis+SpringMVC+M ...
- 【转】Spring+Mybatis+SpringMVC+Maven+MySql搭建实例
林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文主要讲了如何使用Maven来搭建Spring+Mybatis+SpringMVC+M ...
- SpringMVC+Spring+mybatis项目从零开始--Spring mybatis mysql配置实现
上一章我们把SSM项目结构已搭建(SSM框架web项目从零开始--分布式项目结构搭建)完毕,本章将实现Spring,mybatis,mysql等相关配置. 1. 外部架包依赖引入 外部依赖包引入 ...
- Spring MVC+Spring+Mybatis+MySQL(IDEA)入门框架搭建
目录 Spring MVC+Spring+Mybatis+MySQL(IDEA)入门框架搭建 0.项目准备 1.数据持久层Mybatis+MySQL 1.1 MySQL数据准备 1.2 Mybatis ...
随机推荐
- surface RT app安装心得
打开store,然后在键盘输入字母,就出现搜索栏了. 想安装qq,但是输入后找不到软件,原因是我在初始化系统的时候,我的所在地选择的是新加坡,因此找不到软件.在屏幕右下方的setting,然后将所在地 ...
- python基础——函数的参数
python基础——函数的参数 定义函数的时候,我们把参数的名字和位置确定下来,函数的接口定义就完成了.对于函数的调用者来说,只需要知道如何传递正确的参数,以及函数将返回什么样的值就够了,函数内部的复 ...
- (六)STM32的时钟系统
在STM32中,一共有5个时钟源,分别是HSI.HSE.LSI.LSE.PLL (1) HSI是高速内部时钟,RC振荡器,频率为8MHz: (2) HSE是高速外部时钟,可接石英/陶瓷谐振器,或者接外 ...
- Linux用户名显示-bash-4.1$快速排查
最近项目使用的的服务器有点多(100多台),很多开发同事经常问这个问题,现在整理如下: 几个可能导致的原因: 1 用户的家目录所属组被改为root,解决方法使用root执行cd /home/;chow ...
- ajax请求原理及jquery $.ajax封装全解析
.ajax原理: Ajax的原理简单来说通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用javascript来操作DOM而更新页面.这其中最关键的一步就是从服务器获得 ...
- poj 1330 LCA
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #i ...
- SqlServer 临时表 与 表变量(转)
1. 表变量 变量都以@或@@为前缀,表变量是变量的一种,另外一种变量被称为标量(可以理解为标准变量,就是标准数据类型的变量,例如整型int或者日期型DateTime).以@前缀的表变量是本地的,因此 ...
- SQL Server:分离和重新附加数据库
对于分离一个数据库来说,我们可以用Manage Studio界面或者存储过程.但是对于每一种方法都必须保证没有用户使用这个数据库.接下来所讲的都是对于用命令来分离或附加一个数据库.对于用Manage ...
- nodeAPI--FS
fs是唯一一个同时提供同步和异步API的模块: 读取文件夹文件名,数组形式返回: var fs = require('fs'); //async fs.readdir('./',function(er ...
- WCF 超时情形
在做WCF开发时,会经常碰到超时的情况,总结了一下,主要是由一下原因引起: 1.客户端没有正确地Close. 确保每次客户端调用完毕之后,就要调用Close,保证连接数. 另外,服务端配置最大连接数: ...