Java Learning-Programmatic transaction management

Source: Internet
Author: User

Java Learning- Programmatic Transaction Management

Programmatic transactions provide the Transactiontemplate template class, which can greatly reduce the code for transactional operations. So Transactiontemplate uses callback to avoid having developers repeatedly write code that opens transactions, commits transactions, and rolls back transactions, while Transactiontemplate does not need to write a large number of try. Catch block.

650) this.width=650; "Src=" Http://s5.51cto.com/wyfs02/M02/85/21/wKioL1eav2LB0BUDAALL01XhzFQ434.jpg-wh_500x0-wm_3 -wmp_4-s_4251918233.jpg "title=" PHP and Java federated. jpg "alt=" wkiol1eav2lb0budaall01xhzfq434.jpg-wh_50 "/>

Hibernatetemplate must provide an Platformtransactionmanager instance. The instance can be set either manually in code or by using spring's dependency injection. In summary, Transactiontemplate can complete a transactional operation as long as the Platformtransactionmanager reference is obtained.

Using transactiontemplate does not require you to explicitly start a transaction, and you do not even need to commit the transaction explicitly. These steps are done by the template. However, when an exception occurs, the transaction should be explicitly rolled back through the setrollbackonly of the transactionstatus.

the Execute method of Transactiontemplate receives a Transactioncallback instance. Callback is also a classic spring design, to simplify user operations, the following brothers even www.lampbrother.net to help you summarize some Transactioncallback contains the following methods :

Object dolntransaction (transactionstatus status).

The method body of the method is the executing body of the transaction.

If the execution body of the transaction does not have a return value, you can use an instance of the Transactioncallbackwithoutresultl class. This is an abstract class that cannot be instantiated directly and can only be used to create anonymous inner classes. It is also a sub-interface of the Transactioncallback interface, which contains an abstract method:

void Dolntransactionwithoutresult (Transactionstatus status) The method is very similar to the effect of dolntransaction, except that the method has no return value, that is, the transaction execution body does not need to return a value.

In the following example, the Platformtransactionmanager instance implements the class Hibernatetransactionmanager with the transaction manager for Hibernate, which is a local transaction manager, The transaction manager Bean is only deployed in the container, so the transaction manager Bean should be injected into the transactiontemplate in the code. The following is the source code for the configuration file for Hibernate local transaction management:

<?xml version= "1.0" encoding= "gb2312"?>

<! --The DTD definition of the Spring configuration file--

<! DOCTYPE Beans Publ Industrial C "-//spring//dtd bean//en"

"Http://www.springfrarnework.org/dtd/sp Rng-beans.dtd" >

<!--the root element of the Spring configuration file is beans-->

<beans>

<!--define the data source, the Bean's ID is datasource-→

<bean id= "DataSource" class= "Org.springfrarnework.jdbc.datasource.DriverManagerDataSource" >

<!--specified database driver

<property narne= "Driverclassnarne" ><value>corn.rnysql.jdbc.Driver</value></property>

<!--specify url--> to connect to the database

<property narne= "url" ><value>jdbc:rnysql://wonder:3306/j2ee</value></property>

<!--root is the user name of the database--

<property name= "username" ><value>root</value></property>

<!--Pass is a database password--

<property name= "Password" ><value>pass</value></property>

</bean>

<!--define Hibernate's sessionfactory-->

<bean id= "Sessionfactory" class= "Org.springframework.orm.hibernate3.LocalSessionFactoryBean" >

<!--Dependency Injection data source, injected into the datasource--> defined above

<property name= "DataSource" ><ref local= "DataSource"/></property>

<!--The Mappingresouces property is used to list all mapping files >

<property name= "Mappingresources" >

<list>

<!--the following to list all PO mapping files--

<value>lee/MyTest.hbm.xml</value>

</list>

</property>

<!--defines the properties of Hibernate sessionfactory--

<property name= "Hibernateproperties" >

<props>

<!--Specify Hibernate connection Method--

<prop key= "Hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop>

<! Different database connections, startup Select Create, Update, create-drop-->

<prop key= "Hibernate.hbm2ddl.auto" >update</prop>

</props>

</property>

</bean>

<!--configuring Hibernate's transaction manager one)

<!--use the Hibernatetransactionmanager class, which is the Platformtransactionmanager interface for specific implementations that use Hibernate persistence connections. -

<bean id= "TransactionManager" class= "Org.springframework.orm.hibernate3.HibernateTransactionManager" >

<!--hibernatetransactionmanager beans need to be dependent on a reference to inject a sessionfactory bean--

<property name= "Sessionfactory" >

<ref local= "Sessionfactory"/>

</property>

</bean>

</beans>

Here are the transaction operation codes with Transactiontemplate and hibematetemplate:

public class Transactiontest

{

public static void Main (string[] args)

{

Because it is not tested in a web app, you need to manually create a spring context

Final ApplicationContext ctx = new Filesystemxrnlapplicationcontext ("Bean.xml");

The transaction manager that obtains the spring context

Platformtransactionmanager transactionmanager= (Platformtransactionmanager) Ctx.getbean ("TransactionManager");

Final Sessionfactory sessionfactory = (sessionfactory) ctx.getbean ("Sessionfactory");

Create a Transactiontemplate object with the transaction manager instance as a parameter

Transactiontemplate tt = new Transactiontemplate (TransactionManager);

Set transaction propagation properties for Transactiontemplate

Tt. Setpropagationbehavior (transactiondefinition.propagation_requlred);

Executes the Execute method of the Transactiontemplate, which requires an Transactioncallback instance

Tt.execute (New Transactioncallbackwithoutresult ()

Executed in the form of Transactioncallbackwithoutresult anonymous inner class

Protectedvoid Dolntransactionwithoutresult (transactionstatus ts)

Try

{

Create Hibernatetemplate with sessionfactory instance as parameter

Hibernatetemplate hibernatetemplate =

New Hibernatetemplate (sessionfactory);

MYTESTPL = ugly ew MyTest ("Jack");

Save the first Instance

Hibernatetemplate.save (PL);

Let the following database operation throw an exception to see the transaction effect. The previous operation also

will not take effect

MYTESTP2 = new MyTest ("Jack");

To save the second instance, you can set the Name property of the person to the identity property, and

Cause the primary key to repeat the exception, you can see that the previous record is not added to the database

Hibernatetemplate.save (p2);

}

catch (Exception e)

{

Ts.setrollbackonly ();

}

}

});

}

}


Java Learning-Programmatic transaction management

Related Article

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.