018. Spring 声明式事务管理(注解)

来源:互联网 发布:powermill10软件下载 编辑:程序博客网 时间:2024/06/05 03:41

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.annotation.Transactional;import com.spring.dao.UserDao;import com.spring.model.UserModel;import com.spring.service.UserService;@Transactionalpublic class UserServiceImp implements UserService{    private UserDao userDao;    public void setUserDao(UserDao userDao) {        this.userDao = userDao;    }    @Override    public UserModel getUser(int id) {        return userDao.getUser(id);    }    @Override    public void transferMoney(int money, int outId, int inId) {        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"       xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       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         http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx.xsd">    <!-- 数据库配置 -->    <context:property-placeholder location="jdbc.properties"/>    <!-- 数据源 -->    <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>    <!-- JdbcTemplate操作数据库 -->    <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>    <tx:annotation-driven transaction-manager="transactionManager" />    <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>    </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, 146, 148);        }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日志信息 ...
阅读全文
0 0
原创粉丝点击