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) 原子性:事务不可分割 一致性:事务执行的前后,数据完整性保持一致 隔离性:一个事务执行的时候,不应该受到其他事务的打扰 ...
随机推荐
- 技术选型关于redis客户端选择
redis作为分布式缓存框架的首选 相信已经毋庸置疑.能高效.合理的使用好它 必定能提升系统的可用性,高性能.高吞吐量的保障.但选择一个客户端,充分发挥它的能力,就是一个选型问题.现在市场上能选择 ...
- java内部类笔记
内部类 1. 普通内部类 <pre name="code" class="java">class className{ [private|pro ...
- NVL函数:空值转换函数
NVL(表达式1,表达式2) 如果表达式1为空值,NVL返回值为表达式2的值,否则返回表达式1的值. 该函数的目的是把一个空值(null)转换成一个实际的值.其表达式的值可以是数字型.字符型和日期型. ...
- MySQL安装8.0图文教程。超级详细
数据库安装 1.官网下载 接下来点击不用登录注册 2.安装 点击安装服务端 ,然后点击下一步 选择自己安装目录(一定要牢记)这里我选择默认目录,点击下一步 这里弹出警告,直接点击yes 直接点击exe ...
- SQL操作符的优化
操作符优化 IN 操作符 用IN写出来的SQL的优点是比较容易写及清晰易懂,这比较适合现代软件开发的风格. 但是用IN的SQL性能总是比较低的,从ORACLE执行的步骤来分析用IN的SQ ...
- 阿里面试:MySQL如何设计索引更高效?
有情怀,有干货,微信搜索[三太子敖丙]关注这个不一样的程序员. 本文 GitHub https://github.com/JavaFamily 已收录,有一线大厂面试完整考点.资料以及我的系列文章. ...
- git 中.gitignore文件不生效
.gitignore文件 新增忽略文件并没有生效 新增的忽略文件没有生效,是因为git是有缓存的,而之前的文件在缓存中,并不会清除掉,还会继续提交,所以更新.gitignore文件,要清除缓存文件 g ...
- 【SpringBoot1.x】SpringBoot1.x Web 开发
SpringBoot1.x Web 开发 文章源码 简介 SpringBoot 非常适合 Web 应用程序开发.可以使用嵌入式 Tomcat,Jetty 或 Undertow 轻松创建独立的 HTTP ...
- 在阿里云托管的k8s上使用nas做动态存储
前言 关于aliyun托管k8s的存储插件主要有两种: CSI # kubectl get pod -n kube-system | grep csi-plugin csi-plugin-8bbnw ...
- 【ORA】ORA-39002,ORA-39070,ORA-29283, ORA-06512,ORA-29283解决办法
今天使用IMPDP导入的时候报了一个错误 ORA-39002: invalid operation ORA-39070: Unable to open the log file. ORA-2928 ...