Hibernate learning 5 Transaction Management Simple example purchase stock

Source: Internet
Author: User
Tags rollback

The spring and JDBC templates need to be noted:
The Getjdbctemplate template object is multiple, valid only within one method, the current thread is valid, and the system creates a getjdbctemplate template for each method that uses the template object, when
This method is automatically destroyed after it is finished, and is limited to the current method. The use method of this class is wrong and will report null pointer exception
Private JdbcTemplate JT;
Public Studentdaoimpl () {
JT = This.getjdbctemplate ();
}
@Override
public void Insertstudent (Student Student) {
String sql = "INSERT into student (name,age) value (?,?)";
This.jt.update (Sql,student.getname (), Student.getage ());
}
Transaction Management for Spring:
Atomicity: The server layer invokes the DAO layer successfully, unsuccessful and unsuccessful.
The main is to elevate the DAO layer to the server layer
There are typically three ways in which you can manage transactions in spring in the following three ways:
Transactions are system-level services that will appear as slices in the future, to weave what needs to be done into the main business, the pointcut is actually the method of the server layer, as long as the pointcut is specified and the section (transaction) is specified, the transaction can be woven into the server on the method layer (the system-level method invokes AOP (slice), We need to weave the master business, the weaving point is the main business of the server layer to weave the transaction into the server layer method This is the way we achieve
Spring Transaction Management APIs: interfaces
Be sure to remember and understand the memory
Spring rollback WAY: Default: Rollback (critical) occurs when a Run-time exception occurs, commit (compile-time exception) when an exception is found
Runtime exception virtual machine directly hung up, when the exception can be saved by the catch exception by catching exceptions can be set by the programmer to roll back the way
Spring Transaction Definition Interface:
Oracal Isolation level isolation defaults to Level 2
The MySQL default isolation level is level 4
The transaction defines seven transaction propagation behavior constants

This profile does not use transaction management, so when buying a stock, there was a decrease in the amount of account in the database, but the number of shares did not increase.
Let's say one of the demo
First, the entire frame structure.
  
Entity class: Bank account Accoount.java

Package Com.vrv.yinkailong.bean;

Bank account public
class Accoount {
    private Integer aid;
    Private String Aname;     Account name
    private double balance;   Account balance Public
    Accoount () {
        super ();
    }
    Public Accoount (String aname, double balance) {
        super ();
        This.aname = Aname;
        This.balance = balance;
    }
    Public Integer Getaid () {return
        aid;
    }
    public void Setaid (Integer aid) {
        this.aid = aid;
    }
    Public String Getaname () {return
        aname;
    }
    public void Setaname (String aname) {
        this.aname = aname;
    }
    Public double GetBalance () {return
        balance;
    }
    public void setbalance (double balance) {
        this.balance = balance;
    }
    @Override public
    String toString () {return
        "Accoount [aid=] + aid +", aname= "+ Aname +", balance= "+ balance" + "]";
    }

}

Entity class: Stock Account Stock.java

Package Com.vrv.yinkailong.bean;

Stock Account public
class stocks {

    private Integer sid;
    Private String sname;   Stock name
    private int amount;     Number of shares public stock
    () {
        super ();
    }

    Public stock (String sname, int amount) {
        super ();
        This.sname = sname;
        This.amount = amount;
    }
    Public Integer GetSID () {return
        sid;
    }
    public void Setsid (Integer sid) {
        this.sid = sid;
    }
    Public String Getsname () {return
        sname;
    }
    public void Setsname (String sname) {
        this.sname = sname;
    }
    public int Getamount () {return
        amount;
    }
    public void Setamount (int amount) {
        this.amount = amount;
    }
    @Override public
    String toString () {return "the stock
        [sid=" + Sid + ", sname=" + sname + ", amount=" + Amount + "] ";
    }

}

Then the service layer: Define Interface Ibuystockservice.java

Package com.vrv.yinkailong.service;

Import com.vrv.yinkailong.exception.BuyStockException;

Public interface Ibuystockservice {

    //Open account method
    void Openaccouont (String aname,double money);
    void Openstock (String sname,int count);
    Buy stock
    void BuyStock (String aname,double money,string sname,int count) throws buystockexception;

}

Implementation of the interface

Package com.vrv.yinkailong.service;
Import Com.vrv.yinkailong.dao.IAccountDao;
Import Com.vrv.yinkailong.dao.IStockDao;

Import com.vrv.yinkailong.exception.BuyStockException;
        public class Buystockserviceimpl implements Ibuystockservice {private Iaccountdao ADO;


   Private Istockdao Idao;
        It is necessary to realize the Set method public void Setado (Iaccountdao ado) {this.ado = ADO;
        public void Setidao (Istockdao idao) {This.idao = Idao;

    @Override public void Openaccouont (String aname, double) {ado.insertaccount (Aname,money);

    @Override public void Openstock (String sname, int count) {idao.insertstock (sname,count);
          @Override public void BuyStock (string aname, double, string sname, int count) throws Buystockexception {
         Boolean isbuy = true;

         Ado.updateaccount (aname,money,isbuy); Artificially manufacturing the exception and then leads to the transaction * if (true) {THRow new Buystockexception ("Buy stock not successful ...
        But the money was deducted ");
    }*/Idao.updatestock (sname,count,isbuy);
 }



}

Add the corresponding DAO layer, because the corresponding DAO interface is used in the implementation Iaccountdao.java

Package Com.vrv.yinkailong.dao;

Public interface Iaccountdao {

    void Insertaccount (String aname, double);

    void Updateaccount (String aname, double, Boolean isbuy);


Interface: Istockdao.java

Package Com.vrv.yinkailong.dao;

Public interface Istockdao {

    void Insertstock (String sname, int count);

    void Updatestock (String sname, int count, Boolean isbuy);


Implementation of DAO interface Accountdaoimpl.java need to inherit Jdbcdaosupport

Package Com.vrv.yinkailong.daoImpl;

Import Org.springframework.jdbc.core.support.JdbcDaoSupport;

Import Com.vrv.yinkailong.dao.IAccountDao;

public class Accountdaoimpl extends Jdbcdaosupport implements iaccountdao{

    @Override public
    void Insertaccount (String aname, double) {
    String sql = INSERT into account (aname,balance) value (?,?);

    This.getjdbctemplate (). Update (Sql,aname,money);

    @Override public
    void Updateaccount (String aname, double, Boolean isbuy) {/
        /default selling stock
                // In particular, you need the main SQL statement additions and modifications are made on the basis of the original field, do not write the wrong balance
        String sql = "Update account set balance=balance+?" where aname=? ";
        if (isbuy) {
            //= increase the number of shares to buy stock
             sql = "Update account set balance=balance-?" where aname=? ";
        }
       This.getjdbctemplate (). Update (sql,money,aname);

    }

}

Implementation of DAO layer Stockdaoimpl.java the same need to inherit Jdbcdaosupport

Package Com.vrv.yinkailong.daoImpl;

Import Org.springframework.jdbc.core.support.JdbcDaoSupport;

Import Com.vrv.yinkailong.dao.IStockDao;

public class Stockdaoimpl extends Jdbcdaosupport implements Istockdao {

    @Override public
    void Insertstock ( string sname, int count) {
        String sql = INSERT INTO-stock (Sname,amount) value (?,?);

        This.getjdbctemplate (). Update (Sql,sname,count);

    @Override public
    void Updatestock (string sname, int count, Boolean isbuy) {
        //default selling stock
        String sql = Update sto CK set amount=amount-? where sname=? ";
        if (isbuy) {
            //Here adds the stock quantity to buy the stock
             sql = "Update the amount=amount+?  " where sname=? ";
        }
    This.getjdbctemplate (). Update (sql,count,sname);
    }

}

The following is the main configuration file Applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" 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 "> <!---Specify read config file path plus context constraint must introduce corresponding header file common way context constraint--> <contex T:property-placeholder location= "Classpath:jdbc.properties"/> <!---registered data source--> <bean id= "DataSource "class=" Com.mchange.v2.c3p0.ComboPooledDataSource "> <property name=" driverclass "value=" com.mysql.jdbc.Dr Iver "/> <property name= jdbcurl" value= "Jdbc:mysql://127.0.0.1:3306/curd"/> <property nam

         e= "User" value= "root"/><property name= "Password" value= "123456"/> </bean> <!--Specify read profile path plus context constraint must introduce the corresponding header File common way context constraints arbitrary selection of one of the methods can be--> <!--<context:property-placeholder location= "Classpath:jdbc.propert ies "/> <bean id= dataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > <propert

         Y name= "Driverclass" value= "${jdbc.driver}"/> <property name= "Jdbcurl" value= "${jdbc.url}"/>

         <property name= "user" value= "${jdbc.user}"/> <property name= "password" value= "${jdbc.password}"/>
        </bean>--> <bean id= "Iaccountdao" class= "Com.vrv.yinkailong.daoImpl.AccountDaoImpl" > <property name= "DataSource" ref= "DataSource"/> </bean> <bean id= "Istockdao" class= "com . Vrv.yinkailong.daoImpl.StockDaoImpl "> <property name=" dataSource "ref=" DataSource "/> &LT;/BEAN&G

       T <!--registration SerVice--> <bean id= "Buystockservice" class= "Com.vrv.yinkailong.service.BuyStockServiceImpl" > <pro Perty name= "ADO" ref= "Iaccountdao"/> <property name= "Idao" ref= "Istockdao"/> </bean> </bea Ns>

Jdbc.properties configuration file for use

Jdbc.driver=com.mysql.jdbc.driver
Jdbc.url=jdbc:mysql://127.0.0.1:3306/curd
jdbc.user=root

And then the test class Mytest.java

package com.vrv.yinkailong.test;
Import Org.junit.Before;
Import Org.junit.Test;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import com.vrv.yinkailong.exception.BuyStockException;


Import Com.vrv.yinkailong.service.IBuyStockService;

    public class MyTest {private Ibuystockservice service; @Before public void Testbefore () {Classpathxmlapplicationcontext ac = new Classpathxmlapplicationcontext (

         "Applicationcontext.xml");
         Service = (Ibuystockservice) ac.getbean ("Buystockservice");
    System.out.println ("I performed the Before () method");

        @Test public void Testopen () {Service.openaccouont ("John", 10000);
    Service.openstock ("Power Node", 1); //need to handle the checked exception this method is a virtual machine call @Test public void Testbuyaccount () throws Buystockexception {service
    . BuyStock ("John", 500, "Power Node", 5); }
}

The results of the execution at this time are no problem.

But our main study here is transaction processing, it is obvious that the purchase of the stock process is likely to occur abnormal, we need to deal with, here we customize an exception class Buystockexception.java

Package com.vrv.yinkailong.exception;

The purchase of the stock process may be    an exception as long as the inheritance Exception will occur authorization exception, must be processed public
class Buystockexception extends Exception {public

    Buystockexception () {
        super ();
    }

    Public buystockexception (String message) {
        super (message);
    }

}

The temporary code only writes here, if you still need to continue using the transaction to handle the exception, you need to redefine the primary configuration file
This profile does not use transaction management, so when buying a stock, there was a decrease in the amount of account in the database, but the number of shares did not increase.

Using Spring's transaction agent factory management transactions:

This way, you need to create a transaction agent for the target class, the service's implementation class. The class used by the transaction agent is Transactionproxyfactorybean, which needs to initialize some of the following properties:
(1) TransactionManager: Transaction manager
(2) Target: target object, i.e. Ser Vice Implementation class object
(3) Transactionattributes: Transaction property setting
for transaction management in XML configuration proxy mode, the method of rollback of the exception is found by the programmer in the following ways: Through "-exception" mode, can make The transaction is rolled back when the specified exception occurs, and the "+ Exception" method enables the transaction to be committed when the specified exception occurs. The
continues to fill tomorrow. With June, today due to carelessness, in the database encountered some problems, so the progress is a bit slow, tomorrow continue to fill. Thank you for watching

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.