Spring Learning Transaction Management--based on annotation Method (iii)

Source: Internet
Author: User
Tags throwable

Book-type interface

Package Com.spring.tx;public interface Bookshopdao {/** * Search by ISBN add A * @param ISBN * @return */public int FINDBOOKPRICEBYISB  N (string ISBN);/** * Update book Inventory * @param ISBN */public Void Updatebookstock (string ISBN)/** * Update Account * @param username * @param Price */public void Updateuseraccount (String username,int price);}

  

Library Class Realization Class

Package Com.spring.tx;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.jdbc.core.jdbctemplate;import org.springframework.stereotype.Repository; @Repository (" Bookshopdao ") public class Bookshopdaoimpl implements bookshopdao{@Autowiredprivate JdbcTemplate jdbctemplate;@ overridepublic int Findbookpricebyisbn (string ISBN) {String sql = "Select Price from book WHERE ISBN =?"; return jdbctemplate.queryforobject (SQL, INTEGER.CLASS,ISBN);} @Overridepublic void Updatebookstock (String ISBN) {//check inventory is sufficient for string sql = "Select Stock from Book_stock WHERE ISBN =?"; I Nteger queryforobject = jdbctemplate.queryforobject (sql, INTEGER.CLASS,ISBN), if (queryForObject <=0) {throw new Bookstockexception ("Insufficient Stock");} String sql2 = "UPDATE book_stock SET stock = stock-1 WHERE ISBN =?"; Jdbctemplate.update (Sql2, ISBN);} @Overridepublic void Updateuseraccount (string username, int price) {//Verify that the balance is sufficient, if insufficient, throw an exception String sql = "Select Balance from AC Count WHERE username =? "; I Nteger Balance = Jdbctemplate.queryforobject (Sql,integer.class, username), if (Balance<price) {throw new Useraccountexception (" Insufficient balance ");} String sql2= "UPDATE account SET balance = balance-?" WHERE username =? "; Jdbctemplate.update (SQL2, Price,username);}}

  

Book Service

Package Com.spring.tx;public interface Bookshopservice {public void purchase (String username,string ISBN);

  

Library Service Implementation Class

Package Com.spring.tx;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Org.springframework.transaction.annotation.isolation;import Org.springframework.transaction.annotation.propagation;import org.springframework.transaction.annotation.Transactional; @Service ("Bookshopservice") public class Bookshopserviceimpl implements Bookshopservice {@Autowiredprivate Bookshopdao bookshopdao;//add transaction annotations/** * Propagation The propagation behavior of a transaction, that is, when the current transaction method is called by another transaction method, the transaction is appropriate to use the default value of Propagation.required using the method that invokes the transaction (a transaction is shared) * Requires_new The transaction of the method that invokes the transaction is suspended * I Isolation level for solation transactions, commonly used for read_committed * rollbackfor/norollbackfor rollback of all run-time exceptions by default for spring's declarative transactions * readOnly Whether the transaction can take a time to make a forced rollback before the transactions are read-only * timeout @Transactional (propagation=propagation.requires_new,isolation= isolation.read_committed,rollbackfor={useraccountexception.class},readonly=true,timeout=1) @Overridepublic void Purchase (string Username, string ISBN) {//Get unit Price int prices = Bookshopdao.findbookpricebyISBN (ISBN);//Update Inventory Bookshopdao.updatebookstock (ISBN);//Update Account Bookshopdao.updateuseraccount (username, price);}} 

  

Transfers interface

Package Com.spring.tx;import Java.util.list;public interface Cashierservice {public void checkout (String username,list <String> Ibsns);}

  

Transfers Implementation Class

Package Com.spring.tx;import Java.util.list;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import org.springframework.transaction.annotation.Transactional; @Service ("Cashierservice") public class Cashierserviceimpl implements Cashierservice {@Autowiredprivate Bookshopservice Bookshopservice; @Transactional @overridepublic void Checkout (string username, list<string> Ibsns) {for (string Ibsn:ibsns) {bookshopservice.purchase (username, IBSN);}}}

  

Exception Handling Classes

Package Com.spring.tx;public class Bookstockexception extends runtimeexception{/** * */private static final long serialve Rsionuid = 1l;public bookstockexception () {super ();//TODO auto-generated constructor stub}public bookstockexception ( String message, Throwable Cause,boolean enablesuppression, Boolean writablestacktrace) {super (message, cause, Enablesuppression, writablestacktrace);//TODO auto-generated constructor stub}public bookstockexception (String message, Throwable cause) {Super (message, cause);//TODO auto-generated constructor stub}public bookstockexception ( String message) {super (message);//TODO auto-generated constructor stub}public bookstockexception (Throwable cause) { Super (cause);//TODO auto-generated constructor Stub}}package Com.spring.tx;public class Useraccountexception extends runtimeexception{/** * */private static final long serialversionuid = 1l;public useraccountexception () {super ();//TODO A Uto-generated Constructor Stub}public useraccountexception (String MeSsage, Throwable Cause,boolean enablesuppression, Boolean writablestacktrace) {super (message, cause, enablesuppression , writablestacktrace);//TODO auto-generated constructor stub}public useraccountexception (String message, Throwable Cause) {Super (message, cause);//TODO auto-generated constructor stub}public useraccountexception (String message) { Super (message);//TODO auto-generated constructor stub}public useraccountexception (Throwable cause) {super (cause);// TODO auto-generated constructor stub}}

  

Spring configuration file

1 <?XML version= "1.0" encoding= "UTF-8"?>2 <Beansxmlns= "Http://www.springframework.org/schema/beans"3 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4 Xmlns:context= "Http://www.springframework.org/schema/context"5 Xmlns:tx= "Http://www.springframework.org/schema/tx"6 xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd8 Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-4.0.xsd ">9 Ten     <!--Configure automatic scanning of packages - One     <Context:component-scanBase-package= "Com.spring.tx"></Context:component-scan> A     <!--Import Resource File - -     <Context:property-placeholder Location= "Classpath:db.properties" /> -  the     <!--configuring C3P0 Data Sources - -     <BeanID= "DataSource"class= "Com.mchange.v2.c3p0.ComboPooledDataSource"> -         < Propertyname= "User"value= "${jdbc.user}"></ Property> -         < Propertyname= "Password"value= "${jdbc.password}"></ Property> +         < Propertyname= "Jdbcurl"value= "${jdbc.jdbcurl}"></ Property> -         < Propertyname= "Driverclass"value= "${jdbc.driverclass}"></ Property> +  A         < Propertyname= "Initialpoolsize"value= "${jdbc.initpoorsize}"></ Property> at         < Propertyname= "Maxpoolsize"value= "${jdbc.maxpoorsize}"></ Property> -     </Bean> -  -     <!--configuring Spring's JdbcTemplate - -     <BeanID= "JdbcTemplate"class= "Org.springframework.jdbc.core.JdbcTemplate"> -         < Propertyname= "DataSource"ref= "DataSource"></ Property> in     </Bean> -  to     <!--Configure transaction manager - +     <BeanID= "TransactionManager" - class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager"> the         < Propertyname= "DataSource"ref= "DataSource"></ Property> *     </Bean> $ Panax Notoginseng     <!--enable a thing annotation - -     <Tx:annotation-drivenTransaction-manager= "TransactionManager"/> the      + </Beans>

Data source

1 Jdbc.user=root 2 jdbc.password=123456 3 Jdbc.driverclass=com.mysql.jdbc.driver 4 jdbc.jdbcurl=jdbc:mysql:///spring 5 6 jdbc.initpoorsize=5 7 jdbc.maxpoorsize=10

Test class

Package Com.spring.junit;import Java.sql.sqlexception;import Java.util.arrays;import javax.sql.datasource;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Org.springframework.jdbc.core.jdbctemplate;import Com.spring.tx.bookshopdao;import Com.spring.tx.BookShopService ; Import Com.spring.tx.cashierservice;public class Jdbctest {private ApplicationContext ctx =null;private jdbctemplate Jdbctemplate;private Bookshopdao Bookshopdao =null;private bookshopservice bookshopservice=null;private Cashierservice cashierservice = null; {CTX =new classpathxmlapplicationcontext ("Applicationcontext.xml"); JdbcTemplate = (JdbcTemplate) Ctx.getBean (" JdbcTemplate "); Bookshopdao = Ctx.getbean (bookshopdao.class); Bookshopservice =ctx.getbean (BookShopService.class); Cashierservice =ctx.getbean (cashierservice.class);} /** * Test Database connection * @throws SQLException */@Testpublic void Testjdbctest () throws SQLException {DAtasource DataSource = Ctx.getbean (Datasource.class); System.out.println (Datasource.getconnection ());} /** * Execute INSERT Delete update */@Testpublic void Testjdbctemplate () {String sql = "Update test1 set name =? WHERE id =? "; Jdbctemplate.update (SQL, "213", "1");} /** * Test Booksdao */@Testpublic void Testbooksshopdao () {int findbookpricebyisbn = BOOKSHOPDAO.FINDBOOKPRICEBYISBN ("1001 "); Bookshopdao.updatebookstock (" 1001 "); Bookshopdao.updateuseraccount (" 1 ", 100); System.out.println (FINDBOOKPRICEBYISBN);} /** * Test Booksservice */@Testpublic void Testbookshopservice () {bookshopservice.purchase ("1", "1001");} /** * Test Cashierservice */@Testpublic void Testcashierservice () {cashierservice.checkout ("1", Arrays.aslist ("1002", " 1001 "));}}

  

Jar Package

C3p0-0.9.1.2.jar
Com.springsource.net.sf.cglib-2.2.0.jar
Com.springsource.org.aopalliance-1.0.0.jar
Com.springsource.org.aspectj.weaver-1.6.8.release.jar
Commons-logging-1.1.3.jar
Mysql-connector-java-5.1.7-bin.jar
Spring-aop-4.0.0.release.jar
Spring-aspects-4.0.0.release.jar
Spring-beans-4.0.0.release.jar
Spring-context-4.0.0.release.jar
Spring-core-4.0.0.release.jar
Spring-expression-4.0.0.release.jar
Spring-jdbc-4.0.0.release.jar
Spring-orm-4.0.0.release.jar
Spring-tx-4.0.0.release.jar
Spring-web-4.0.0.release.jar
Spring-webmvc-4.0.0.release.jar

Spring Learning Transaction Management--based on annotation Method (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.