Spring_ Transaction-Annotation Code

Source: Internet
Author: User
Tags throwable

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: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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd ">

<context:component-scan base-package= "Com.atguigu.spring" ></context:component-scan>

<!--importing resource files--
<context:property-placeholder location= "Classpath:db.properties"/>

<!--configuring C3P0 data Sources--
<bean id= "DataSource"
class= "Com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name= "user" value= "${jdbc.user}" ></property>
<property name= "Password" value= "${jdbc.password}" ></property>
<property name= "Jdbcurl" value= "${jdbc.jdbcurl}" ></property>
<property name= "Driverclass" value= "${jdbc.driverclass}" ></property>

<property name= "initialpoolsize" value= "${jdbc.initpoolsize}" ></property>
<property name= "maxpoolsize" value= "${jdbc.maxpoolsize}" ></property>
</bean>

<!--configuration Spirng JdbcTemplate--
<bean id= "JdbcTemplate"
class= "Org.springframework.jdbc.core.JdbcTemplate" >
<property name= "DataSource" ref= "DataSource" ></property>
</bean>

<!--configuration Namedparameterjdbctemplate, the object can make the appliance name parameter, which has no parameterless constructor, so you must specify parameters for its constructor--
<bean id= "Namedparameterjdbctemplate"
class= "Org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" >
<constructor-arg ref= "DataSource" ></constructor-arg>
</bean>

<!--configuration Transaction Manager-
<bean id= "TransactionManager"
class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name= "DataSource" ref= "DataSource" ></property>
</bean>

<!--enable transaction annotations--
<tx:annotation-driven transaction-manager= "TransactionManager"/>

</beans>

Bookshopdao.java

Package com.atguigu.spring.tx;

Public interface Bookshopdao {

Get the price of the book according to the ISBN
public int FINDBOOKPRICEBYISBN (String ISBN);

Update the inventory for the number. Inventory for the ISBN 1
public void Updatebookstock (String ISBN);

Update user's account balance: Make Username's balance-price
public void Updateuseraccount (String username, int. price);
}

Bookshopdaoimpl.java

Package com.atguigu.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 {

@Autowired
Private JdbcTemplate JdbcTemplate;

@Override
public int FINDBOOKPRICEBYISBN (String ISBN) {
String sql = "Select Price from book WHERE ISBN =?";
return jdbctemplate.queryforobject (SQL, Integer.class, ISBN);
}

@Override
public void Updatebookstock (String ISBN) {
Check the inventory is sufficient, if not enough, throw an exception
String sql2 = "Select Stock from Book_stock WHERE ISBN =?";
int stock = Jdbctemplate.queryforobject (Sql2, Integer.class, ISBN);
if (stock = = 0) {
throw new Bookstockexception ("Insufficient stock!");
}

String sql = "UPDATE book_stock SET stock = stock-1 WHERE ISBN =?";
Jdbctemplate.update (sql, ISBN);
}

@Override
public void Updateuseraccount (String username, int. price) {
Verify that the balance is sufficient and throws an exception if it is insufficient
String sql2 = "Select Balance from account WHERE username =?";
int balance = Jdbctemplate.queryforobject (SQL2, Integer.class, username);
if (balance < price) {
throw new Useraccountexception ("Insufficient balance!");
}

String sql = "UPDATE account SET balance = balance-?" WHERE username =? ";
Jdbctemplate.update (SQL, price, username);
}

}

Bookshopservice.java

Package com.atguigu.spring.tx;

Public interface Bookshopservice {

public void Purchase (string username, string ISBN);

}

Bookshopserviceimpl.java

Package com.atguigu.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 {

@Autowired
Private Bookshopdao Bookshopdao;

Add transaction annotations
1. Use propagation to specify the propagation behavior of the transaction, that is, when the current transaction method is invoked by another transaction method
How transactions are used, the default value is REQUIRED, which is the transaction using the calling method
Requires_new: The transaction for the transaction's own transaction, the transaction that invoked the method is suspended.
2. Use isolation to specify the isolation level of the transaction, the most commonly used value is read_committed
3. By default, Spring's declarative transactions roll back all run-time exceptions. You can also use the corresponding
property to set. The default value is usually the case.
4. Use ReadOnly to specify whether the transaction is read-only. Indicates that the transaction reads only the data but does not update the data.
This helps the database engine to optimize transactions. If it's true. A method that only reads the database values, you should set the Readonly=true
5. Use timeout to specify the amount of time a transaction can take before forcing a rollback.
@Transactional (Propagation=propagation.requires_new,
Isolation=isolation.read_committed,
Norollbackfor={useraccountexception.class})
@Transactional (Propagation=propagation.requires_new,
Isolation=isolation.read_committed,
Readonly=false,
timeout=3)
@Override
public void Purchase (string username, String ISBN) {

try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {}

1. Get the price of the book
int price = BOOKSHOPDAO.FINDBOOKPRICEBYISBN (ISBN);

2. Inventory of updated numbers
Bookshopdao.updatebookstock (ISBN);

3. Update User Balances
Bookshopdao.updateuseraccount (username, price);
}

}

Cashier.java

Package com.atguigu.spring.tx;

Import java.util.List;

Public interface Cashier {

public void Checkout (String username, list<string> ISBNs);

}

Cashierimpl.java

Package com.atguigu.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 ("cashier")
public class Cashierimpl implements cashier {

@Autowired
Private Bookshopservice Bookshopservice;

@Transactional
@Override
public void Checkout (String username, list<string> ISBNs) {
for (String Isbn:isbns) {
Bookshopservice.purchase (username, ISBN);
}
}

}

Bookstockexception.java

Package com.atguigu.spring.tx;

public class Bookstockexception extends runtimeexception{

/**
*
*/
Private static final long serialversionuid = 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
}


}

Useraccountexception.java

Package com.atguigu.spring.tx;

public class Useraccountexception extends runtimeexception{

/**
*
*/
Private static final long serialversionuid = 1L;

Public Useraccountexception () {
Super ();
TODO auto-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
}



}

Springtransactiontest.java

Package com.atguigu.spring.tx;

Import static org.junit.assert.*;

Import Java.util.Arrays;

Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

public class Springtransactiontest {

Private ApplicationContext CTX = null;
Private Bookshopdao Bookshopdao = null;
Private Bookshopservice bookshopservice = null;
Private Cashier cashier = NULL;

{
CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
Bookshopdao = Ctx.getbean (Bookshopdao.class);
Bookshopservice = Ctx.getbean (Bookshopservice.class);
Cashier = Ctx.getbean (Cashier.class);
}

@Test
public void Testtransactionlpropagation () {
Cashier.checkout ("AA", Arrays.aslist ("1001", " 1002 "));
}

@Test
public void Testbookshopservice () {
Bookshopservice.purchase ("AA", "1001");
}

@Test
public void Testbookshopdaoupdateuseraccount () {
Bookshopdao.updateuseraccount ("AA", +);
}

@Test
public void Testbookshopdaoupdatebookstock () {
Bookshopdao.updatebookstock ("1001");
}

@Test
public void Testbookshopdaofindpricebyisbn () {
System.out.println ( BOOKSHOPDAO.FINDBOOKPRICEBYISBN ("1001"));
}

}

Spring_ Transaction-Annotation Code

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.