Spring框架——事务管理方式搭建一个小的项目
学习Spring框架,通过事务管理的方式搭建一个小的项目,该项目可以查询对数据库中的图书库存数量进行修改。
首先,使用MVC分层的设计模式思想搭建项目目录结构。
此部分代码源码之中都有相关注释,所以尽情附上源码。
首先Dao层的源码:
package com.jredu.book.Dao;
public interface BookDao {
/**
* 通过编号查询书的价格
* @param isbn
* @return
*/
int findBookPriceByIsbn(String isbn);
/**
* 通过用户名查询余额
* @param username
* @return
*/
int findBalanceByUsername(String username);
/**
* 更新书的库存
* @param isbn
*/
void updateBookStock(String isbn,int stock);
/**
* 通过编号查询库存数量
* @param isbn
* @return
*/
int findStockByIsbn(String isbn);
/**
* 更新用户余额信息
* @param username
* @param price
*/
void updateAccountBalance(String username,int price);
}
dao.impl相关的源码:
package com.jredu.book.Dao.Impl;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.jredu.book.Dao.BookDao;
import com.jredu.book.entity.Account;
import com.jredu.book.entity.Book;
@Repository
public class BookDaoImpl extends JdbcDaoSupport implements BookDao{
@Autowired
public void setDS(DataSource dataSource){
setDataSource(dataSource);
}
@Override
public int findStockByIsbn(String isbn) {
// TODO Auto-generated method stub
String sql = "select * from book_stock where isbn=?";
Map<String, Object> bookStock= getJdbcTemplate().queryForMap(sql,isbn);
int stock = Integer.parseInt(bookStock.get("stock").toString());
return stock;
}
@Override
public int findBookPriceByIsbn(String isbn) {
// TODO Auto-generated method stub
String sql="select * from book where isbn=?";
Book book = getJdbcTemplate().queryForObject(sql, new Book(), isbn);
return book.getPrice();
}
@Override
public int findBalanceByUsername(String username) {
// TODO Auto-generated method stub
String sql = "select * from account where username=?";
Account account = getJdbcTemplate().queryForObject(sql, new Account(),username);
return account.getBalance();
}
@Override
public void updateBookStock(String isbn,int stock) {
// TODO Auto-generated method stub
String sql="update book_stock set stock=? where isbn=?";
getJdbcTemplate().update(sql,stock,isbn);
}
@Override
public void updateAccountBalance(String username, int price) {
// TODO Auto-generated method stub
String sql="update account set balance=? where username=?";
getJdbcTemplate().update(sql,price,username);
}
}
entity实体类的相关源码:
package com.jredu.book.entity;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class Account implements RowMapper<Account>{
private String username;
private int balance;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
@Override
public Account mapRow(ResultSet rs, int arg1) throws SQLException {
// TODO Auto-generated method stub
Account account = new Account();
account.setUsername(rs.getString("username"));
account.setBalance(rs.getInt("balance"));
return account;
}
}
package com.jredu.book.entity;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class Book implements RowMapper<Book>{
private String isbn;
private String bookName;
private int price;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public Book mapRow(ResultSet rs, int arg1) throws SQLException {
// TODO Auto-generated method stub
Book book = new Book();
book.setIsbn(rs.getString("isbn"));
book.setBookName(rs.getString("book_name"));
book.setPrice(rs.getInt("price"));
return book;
}
}
service目录下的相关源码:
package com.jredu.book.service;
public interface BookService {
void purchase(String isbn,String username);
}
package com.jredu.book.service;
public interface MoneyService {
void purchase(String isbn,String username);
}
service接口即service.impl目录下的相关源码:
package com.jredu.book.service.Impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.jredu.book.Dao.BookDao;
import com.jredu.book.service.BookService;
@Repository
public class BookServiceImpl implements BookService{
@Autowired
private BookDao dao;
@Override
public void purchase(String isbn, String username) {
// TODO Auto-generated method stub
int stock = dao.findStockByIsbn(isbn);
//库存要大于1本
if(stock>0){
int price = dao.findBookPriceByIsbn(isbn);
int balance = dao.findBalanceByUsername(username);
//余额是否大于书的价格
if(balance>=price){
//执行更新余额信息
dao.updateAccountBalance(username, balance-price);
//更新库存信息
dao.updateBookStock(isbn, stock-1);
}
}
}
}
编写一个测试类,book.test目录下测试类源码:
package com.jredu.book.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jredu.book.service.BookService;
import com.jredu.book.service.MoneyService;
public class BookTest {
public static void main(String[] args) {
ApplicationContext app= new ClassPathXmlApplicationContext("applicationContext-book.xml");
BookService service = app.getBean(BookService.class);
service.purchase("abc","wang");
System.out.println("业务完成");
}
}
最重要的部分是配置application-book.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
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/util
http://www.springframework.org/schema/util/spring-util.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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.jredu.book"></context:component-scan>
<!-- 配置C3P0数据源 -->
<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean
id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
p:user="${jdbc.user}"
p:password="${jdbc.pwd}"
p:driverClass="${jdbc.driverClassName}"
p:jdbcUrl="${jdbc.url}"
p:initialPoolSize="${jdbc.initPoolSize}"
p:maxPoolSize="${jdbc.maxPoolSize}"
/>
<!-- 配置事务管理器 -->
<bean
id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"
/>
<!-- 事务的通知 -->
<tx:advice
id="booktxAdvice" transaction-manager="transactionManager"
>
<tx:attributes>
<tx:method name="purchase*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution (* com.jredu.book.service.*.*(..))" id="pointcut"/>
<aop:advisor advice-ref="booktxAdvice" pointcut-ref="pointcut"/>
</aop:config>
<!-- 配置JDBC Template -->
<bean
id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"
/>
</beans>
至此,使用事务方式搭建的一个小项目就已经完成,操作完成后,数据库中的图书库存数量会有所变化。
Spring框架——事务管理方式搭建一个小的项目的更多相关文章
- Intellij IDEA采用Maven+Spring MVC+Hibernate的架构搭建一个java web项目
原文:Java web 项目搭建 Java web 项目搭建 简介 在上一节java web环境搭建中,我们配置了开发java web项目最基本的环境,现在我们将采用Spring MVC+Spring ...
- Spring框架事务支持模型的优势
全局事务 全局事务支持对多个事务性资源的操作,通常是关系型数据库和消息队列.应用服务器通过JTA管理全局性事务,API非常烦琐.UserTransaction通常需要从JNDI获取,意味着需要与JND ...
- 二十 Spring的事务管理及其API&事务的传播行为,编程式&声明式(xml式&注解式,底层AOP),转账案例
Spring提供两种事务方式:编程式和声明式(重点) 前者需要手写代码,后者通过配置实现. 事务的回顾: 事务:逻辑上的一组操作,组成这组事务的各个单元,要么全部成功,要么全部失败 事务的特性:ACI ...
- Mybatis事务(一)事务管理方式
Mybatis管理事务是分为两种方式: (1)使用JDBC的事务管理机制,就是利用java.sql.Connection对象完成对事务的提交 (2)使用MANAGED的事务管理机制,这种机制mybat ...
- 【Spring】Spring的事务管理 - 2、声明式事务管理(实现基于XML、Annotation的方式。)
声明式事务管理 文章目录 声明式事务管理 基于XML方式的声明式事务 基于Annotation方式的声明式事务 简单记录 - 简单记录-Java EE企业级应用开发教程(Spring+Spring M ...
- spring事务管理方式,aop
达内12 note unit 09 01 1.spring事务管理 2.spring提供了对事务管理支持 spring采用aop机制完成事务控制 可以实现在不修改原有组件代码情况下实现事务控制功能. ...
- Spring事务管理详解_基本原理_事务管理方式
1. 事务的基本原理 Spring事务的本质其实就是数据库对事务的支持,使用JDBC的事务管理机制,就是利用java.sql.Connection对象完成对事务的提交,那在没有Spring帮我们管理事 ...
- 事务有哪些特性?spring的事务管理有几种方式实现,如何实现?
特性:1.原子性:一个事务中所有对数据库的操作是一个不可分割的操作序列,要么全做要么全不做 2.一致性:数据不会因为事务的执行而遭到破坏 3.隔离性:一个事物的执行,不受其他事务的干扰,即并发执行的事 ...
- Spring的事务管理
事务 事务:是逻辑上一组操作,要么全都成功,要么全都失败. 事务特性(ACID) 原子性:事务不可分割 一致性:事务执行的前后,数据完整性保持一致 隔离性:一个事务执行的时候,不应该受到其他事务的打扰 ...
随机推荐
- HttpMessageConverter那回事
相信使用过Spring的开发人员都用过@RequestBody.@ResponseBody注解,可以直接将输入解析成Json.将输出解析成Json,但HTTP 请求和响应是基于文本的,意味着浏览器和服 ...
- 一个坑,bootstrap selectpicker 重置下拉列表时遇到的问题
需求是这样的:点击右侧三个按钮中的任意一个,如果执行成功,左侧的版本信息就需要重新获取列表.挺简单的需求,但是遇到了一个坑, 在使用$('#id').html('')清空下拉选项并且重新赋值的时候,始 ...
- 腾讯IOT安卓开发初探
目录 腾讯IOT 安卓开发初探 Tecent IOT 开发平台的使用 新建项目 创建产品 添加自定义功能 设备开发 微信小程序配置 面板配置 新建设备 使用设备 安卓开发 前置配置 data.json ...
- 《Go 语言并发之道》读后感 - 第一章
<Go 语言并发之道>读后感 - 第一章 前言 人生路漫漫,总有一本书帮助你在某条道路上打通任督二脉,<Go 语言并发之道>就是我作为一个 Gopher 道路上的一本打通任督二 ...
- Sublime Text 3 习惯插件 转
原帖:https://www.cnblogs.com/hykun/p/sublimeText3.html Emmet插件 Emmet插件可以说是使用Sublime Text进行前端开发必不可少的插件 ...
- 伪静态 RewriteRule-htaccess
伪静态实际上是利用PHP把当前地址解析成另一种方法来访问网站,要学伪静态规则的写法,要懂一点正则 一.正则表达式教程 有一个经典的教程:正则表达式30分钟入门教程 常用正则如下: . 换行符以外的所有 ...
- DEDECMS自动编号(序号)autoindex属性(转)
版权声明:本文为博主原创文章,未经博主允许不得转载. 让织梦dedecms autoindex,itemindex 从0到1开始的办法! 1 2 3 [field:global name=autoin ...
- 【Java基础】Java11 新特性
Java11 新特性 新增字符串处理方法 新增方法: 判断字符串是否为空白 " ".isBlank(); // true 去除首尾空白 " Javastack " ...
- 【JavaWeb】HTML&CSS 基础
HTML&CSS 基础 HTML 基础 HTML 标签 HTML标题:HTML 标题(Heading)是通过 h1 - h6 等标签进行定义的. HTML段落: HTML 段落是通过 p 标签 ...
- 【SpringBoot1.x】SpringBoot1.x Web 开发
SpringBoot1.x Web 开发 文章源码 简介 SpringBoot 非常适合 Web 应用程序开发.可以使用嵌入式 Tomcat,Jetty 或 Undertow 轻松创建独立的 HTTP ...