016. Spring 编程式事务管理

来源:互联网 发布:手游源码出售平台 编辑:程序博客网 时间:2024/06/10 07:34

1、创建Java项目:File -> New -> Java Project

2、项目结构
这里写图片描述

3、必要jar包
这里写图片描述

4、创建数据库,使用MySQL数据库

SET NAMES GBK;CREATE DATABASE IF NOT EXISTS `db_spring`;USE `db_spring`;DROP TABLE IF EXISTS `tb_user`;CREATE TABLE `tb_user`(    `id` INTEGER PRIMARY KEY NOT NULL,    `name` VARCHAR(16) NOT NULL,    `pswd` VARCHAR(32) NOT NULL,    `money` INTEGER DEFAULT 500)ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `tb_user`(`id`, `name`, `pswd`) VALUES(146, '吴腾辉', '105032014146'), (148, '吴钟灯', '105032014148');

5、创建UserModel实体类UserModel.java

package com.spring.model;public class UserModel {    private int id;    private String name;    private String pswd;    private int money;    public UserModel(){}    public UserModel(int id, String name, String pswd, int money) {        super();        this.id = id;        this.name = name;        this.pswd = pswd;        this.money = money;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPswd() {        return pswd;    }    public void setPswd(String pswd) {        this.pswd = pswd;    }    public int getMoney() {        return money;    }    public void setMoney(int money) {        this.money = money;    }    @Override    public String toString() {        return "UserModel [id=" + id + ", name=" + name + ", pswd=" + pswd + ", money=" + money + "]";    }}

6、创建UserDao接口UserDao.java

package com.spring.dao;import com.spring.model.UserModel;public interface UserDao {    public UserModel getUser(int id);    public int inMoney(int money, int id);    public int outMoney(int money, int id);}

7、创建UserDaoImp实现类UserDaoImp.java

package com.spring.dao.imp;import java.sql.ResultSet;import java.sql.SQLException;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowCallbackHandler;import com.spring.dao.UserDao;import com.spring.model.UserModel;public class UserDaoImp implements UserDao {    private JdbcTemplate jdbcTemplate = null;    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {        this.jdbcTemplate = jdbcTemplate;    }    @Override    public UserModel getUser(int id) {        String sql = "select id, name, pswd, money from tb_user where id=?";        UserModel user = new UserModel();        jdbcTemplate.query(sql, new RowCallbackHandler(){            @Override            public void processRow(ResultSet rs) throws SQLException {                user.setId(rs.getInt("id"));                user.setName(rs.getString("name"));                user.setPswd(rs.getString("pswd"));                user.setMoney(rs.getInt("money"));            }        }, id);        return user;    }    @Override    public int inMoney(int money, int id) {        String sql = "update tb_user_error set money=money+? where id=?";        return jdbcTemplate.update(sql, money, id);    }    @Override    public int outMoney(int money, int id) {        String sql = "update tb_user set money=money-? where id=?";        return jdbcTemplate.update(sql, money, id);    }}

8、创建UserService接口UserService.java

package com.spring.service;import com.spring.model.UserModel;public interface UserService {    public UserModel getUser(int id);    public void transferMoney(int money, int outId, int inId);}

9、创建UserServiceImp实现类UserServiceImp.java

package com.spring.service.imp;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;import com.spring.dao.UserDao;import com.spring.model.UserModel;import com.spring.service.UserService;public class UserServiceImp implements UserService{    private UserDao userDao;    private TransactionTemplate transactionTemplate;    public void setUserDao(UserDao userDao) {        this.userDao = userDao;    }    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {        this.transactionTemplate = transactionTemplate;    }    @Override    public UserModel getUser(int id) {        return userDao.getUser(id);    }    @Override    public void transferMoney(int money, int outId, int inId) {        transactionTemplate.execute(new TransactionCallbackWithoutResult() {            @Override            protected void doInTransactionWithoutResult(TransactionStatus arg0) {                userDao.outMoney(money, outId);                userDao.inMoney(money, inId);            }        });    }}

10、创建数据库配置文件jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/db_springjdbc.username=rootjdbc.password=

11、创建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"       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">    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">        <property name="driverClassName" value="${jdbc.driverClassName}"/>        <property name="url" value="${jdbc.url}"/>        <property name="username" value="${jdbc.username}"/>        <property name="password" value="${jdbc.password}"/>    </bean>    <context:property-placeholder location="jdbc.properties"/>    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource" ref="dataSource"></property>    </bean>    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource"></property>    </bean>    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">        <property name="transactionManager" ref="transactionManager"></property>    </bean>    <bean id="userDao" class="com.spring.dao.imp.UserDaoImp">        <property name="jdbcTemplate" ref="jdbcTemplate"></property>    </bean>    <bean id="userService" class="com.spring.service.imp.UserServiceImp">        <property name="userDao" ref="userDao"></property>        <property name="transactionTemplate" ref="transactionTemplate"></property>    </bean></beans>

12、创建Spring测试类SpringUnit.java

package com.spring.junit;import org.junit.After;import org.junit.Before;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.spring.service.UserService;public class SpringUnit {    ClassPathXmlApplicationContext ctx = null;    @Before    public void setUp() throws Exception {        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");    }    @After    public void tearDown() throws Exception {        ctx.close();    }    @Test    public void test() {        UserService userService = (UserService) ctx.getBean("userService");        try{            userService.transferMoney(50, 148, 146);        }catch(Exception e){            System.out.println(e.getMessage());        }        System.out.println(userService.getUser(146).toString());        System.out.println(userService.getUser(148).toString());    }}

13、测试结果

... 省略Spring日志信息 ...PreparedStatementCallback; bad SQL grammar [update tb_user_error set money=money+? where id=?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'db_spring.tb_user_error' doesn’t existUserModel [id=146, name=吴腾辉, pswd=105032014146, money=500]UserModel [id=148, name=吴钟灯, pswd=105032014148, money=500]... 省略Spring日志信息 ...
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 哪些人不适合用木香顺气丸 补脾益肠丸不适合什么人吃 龙胆泄肝丸不适用那些人 什么人不能吃五子洐宗丸 大活络丸哪些人不能吃 骨化三醇胶丸适合适合什么人 什么人不宜吃麝香保心丸 天王补心丸不适合什么人吃 人参保肺丸 香砂养胃丸不适合什么人吃 香砂六君子丸不适合哪些人 补脾益肠丸适合什么人吃 藿香正气丸什么人不能吃 安神补心丸适合哪些人吃 什么人不适合吃柏子养心丸 木香顺气丸不适合哪些人吃 泰国蜈蚣丸哪些人禁用 小活络丸哪些人不能用 2陈丸哪种人不能吃 大补阴丸适合什么人吃 黑芝麻丸不适合什么人吃 清心丸适合什么人吃 安宫丸什么人不能吃 兰丸多人上受 舒肝健胃丸不适合什么人吃 丹栀逍遥丸适合哪些人 人丹 什么人不适合吃红毛丹 哪些人不适合吃香丹清 丹叁粉哪种人不能吃 丹栀逍遥丸什么人不能吃 百消丹不适用于什么人 哪些人不能吃摩罗丹 环阳丹医生江涛是何许人 丹人修仙之仙界篇 全家人的丹尼斯供应商 全家人的丹尼斯大卖场供应商 艳鼎丹仙 那时那人 什么人不能吃天王补心丹 大活络丹不适合什么人 全家人的丹尼斯供应商口令