Using Spring to manage things

Source: Internet
Author: User
Tags commit exception handling oracleconnection require rollback

1, Programming things

Programming refers to the implementation of things by coding, that is, like JDBC programming to implement things management

Spring's support for programmatic things

The things in spring can be divided into physical things and logical things;

Physical things: The things that are provided by the underlying database, such as JDBC or JTA;

Logical things: Spring-managed things, different from physical things, logical things provide richer control and if you want to get the benefits of spring transaction management you must use logical transactions, so in spring if you don't specifically emphasize logical transactions

Spring offers two programmatic things: using Platformtransactionmanager directly to implement and use the Transactiontemplate template class to support logical management of things.

1.1, direct use of platformtransactiontemplatemanager for programmatic management of things

Platformtransactiontemplatemanager implement, then combine transactiondefinition to open things, and combine transactionstatus to roll back and forth or submit things, You can complete the whole thing management for the current object.

The disadvantage of using it is also obvious, from the perspective of application development, too low-level, different things management API caused by the difference is too large, exception handling can become cumbersome, the number of code duplication will be amazing.

Here's how I use Platformtransactiontemplatemanager to manage things:

1. Data sources and things Manager-defined configuration files

         <!--datasource for Oracle-->
	<bean id= "DataSource"
		Org.springframework.jdbc.datasource.DriverManagerDataSource "
		destroy-method=" Close ">
		<property Name= "Driverclassname" value= "Oracle.jdbc.driver.OracleDriver" ></property>
		<property "url" Value= "Jdbc:oracle:thin: @localhost: 1521:orcl" ></property>
		<property name= "username" value= "Scott "></property>
		<property name=" password "value=" 123 "></property>
	</bean>

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

2. SQL used in testing:

public class Springtransactiontest {
	/**
	 * ready to test using SQL/
	private static final String Insert_sql = " INSERT into TD (User_name,password) VALUES (?,?) ";
	private static final String count_sql = "Select COUNT (*) from TD";

3. Initialize the Spring container:

/**
	 * Initialize Spring container
	/private static ApplicationContext ctx;
	private static Platformtransactionmanager Txmanager;
	private static DataSource DataSource;
	private static JdbcTemplate JdbcTemplate;

	@BeforeClass public
	static void SetupClass () {
		CTX = new Classpathxmlapplicationcontext ("/ Applicationcontext.xml ");
		Txmanager = (Platformtransactionmanager) ctx.getbean ("TransactionManager");
		DataSource = (DataSource) ctx.getbean ("DataSource");
		JdbcTemplate = new JdbcTemplate (dataSource);
	}	

4, use the high level jdbctemplate to carry on the transaction manager test

/** * Use high level jdbctemplate for things manager test/@Test public void Testplatformtransactionmanager () {/** * Defaulttrans Actiondefinition: Transaction definition, definition such as isolation level, propagation behavior, in this example, the isolation level is isolation_read_committed (commit read), * Propagate behavior is propagation_
		 REQUIRED (Must have transaction support, that is, if there is currently no transaction, create a new transaction, if already exist in a transaction, join in this transaction). * Dbctemplate: Performs the appropriate SQL operation through the JdbcTemplate object and automatically enjoys transaction support, noting that the transaction is thread-bound, so the transaction manager can run in a multithreaded environment; * TXMANAGER.COMMIT (status)
		 : Commits the transaction bound by the status object; * Txmanager.rollback (status): Rolls back the transaction bound by the status object when an exception is encountered. * Transactionstatus: Transaction state class, obtained by the Platformtransactionmanager Gettransaction method based on the transaction definition, when the transaction state is obtained, spring is based on the propagation behavior.
		How to open a business;/defaulttransactiondefinition def = new Defaulttransactiondefinition ();
		Def.setisolationlevel (transactiondefinition.isolation_read_committed);
		Def.setpropagationbehavior (transactiondefinition.propagation_required);
		/** * Gettransaction Open a thing * * transactionstatus status = Txmanager.gettransaction (Def);
			try {System.out.println (Jdbctemplate.queryforint (count_sql)); TxManager.commit (status);
		catch (RuntimeException e) {txmanager.rollback (status);

 }
	}

5. Use low-level solutions for Transaction manager testing

/** * Use a low-level solution for things manager testing * @throws SQLException/@Test public void Testplatformtran
		Sactionmanagerforlowlevel () {defaulttransactiondefinition def=new defaulttransactiondefinition ();
		Def.setisolationlevel (transactiondefinition.isolation_read_committed);
		Def.setpropagationbehavior (transactiondefinition.propagation_required);
		Transactionstatus status=txmanager.gettransaction (def); Because I am using Oracle, I use OracleConnection oracleconnection conn= (oracleconnection) datasourceutils.getconnection (
		DataSource);
			try {preparedstatement ps=conn.preparestatement (insert_sql);
			Ps.setstring (1, "CCC");
			Ps.setstring (2, "222");
			Ps.execute ();  Txmanager.commit (status); Before the submission of the database has not been inserted into the data, the original need to submit, thanks to the younger brother reminded, good to learn from others} catch (Exception e) {//Because I inserted a lot of this, but has not been submitted, so ID increased to 43,  
		      The results of the submission, however, were the result of the subsequent submission status.setrollbackonly (); 
		Txmanager.rollback (status);
		}finally{datasourceutils.releaseconnection (conn, dataSource); }
	}	

It is not recommended to use Datasourceutils to acquire and release connections in low-level scenarios, to use Txmanager to open management transactions, and to program to JDBC, which is much more cumbersome and complex than a template class approach


1.2, using transactiontemplate for programming things to manage

The process of using platformtransactionmanager to manage things is fixed, and only part of the logic of the various things is different during the management period, you can consider the way of combining the template method pattern with callback, like the Springde data access layer. Encapsulation of the code that directly uses Platformtransactionmanager for management of things, so that there is a more convenient way of programming things to manage, that is, to use transactiontemplate programming things to manage. Org.springframework.transaction.support.TransactionTemplate encapsulates the Platformtransactionmanager-related things and related exception handling, and the developer has more Focus on providing specific definition content through the corresponding callback interface. Spring provides two callback callback interfaces for Transactiontemplate

Transactioncallback: By implementing the "T Dointransaction (transactionstatus status)" of this interface method to define the operation code that requires transaction management Transactioncallbackwithoutresult: Inherits the Transactioncallback interface, provides "void Dointransactionwithoutresult" ( Transactionstatus status) "The convenience interface is used to facilitate transaction operation code that does not require a return value.

The following is the use of the Transactiontemplate template class:

         /**
	 * Use  the Transactiontemplate template class for simplifying things management, which is defined by the template class
	 * The specific operation is specified by the Transactioncallback interface or the Transactioncallbackwithoutresult callback interface
	 * Every day has things to manage code, but by the template class to complete things management, so much simpler.
	@Test public
	void Testtransactiontemplate () {
		transactiontemplate transactiontemplate=new Transactiontemplate (Txmanager);
		Transactiontemplate.setisolationlevel (transactiondefinition.isolation_read_committed);
		Transactiontemplate.execute (New Transactioncallbackwithoutresult () {

			@Override
			protected void Dointransactionwithoutresult (Transactionstatus arg0) {
				//jdbctemplate.update (insert_sql, "JC", "333");
				Jdbctemplate.update (Insert_sql, New object[]{"JC", "333"});
			}
		

Transactiontemplate: Creates a transaction template class from New Transactiontemplate (Txmanager), where constructor parameters are implemented Platformtransactionmanager, and through its corresponding method to set the transaction definition, such as the transaction isolation level, the propagation behavior, and so on, does not specify the propagation behavior here, its tacit thought propagation_required;

Transactioncallbackwithoutresult: A callback implementation without return is used here, and its Dointransactionwithoutresult method implementation defines operations that require transaction management;

Transactiontemplate.execute (): This method performs a callback that requires transaction management.


For JTA distributed things I have not achieved here. It's too much trouble.
Through the above practice, I will basically use Platformtransactionmanager and transactiontemplate for simple transaction processing, how to apply to the actual project.
I will implement it in the next blog post.


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.