Using Spring for things management

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

1. Programming Things

The so-called programming thing refers to the implementation of things by encoding, that is, similar to JDBC programming to achieve the management of things

Spring's support for programmatic things

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

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

Logical things: Things that spring manages, different from physical things, logical things provide richer control, and if you want the benefits of spring transaction management, you must use logical transactions, so in spring if you do not specifically emphasize logical transactions

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

1.1, direct use of platformtransactiontemplatemanager for programming things management

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

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

Here's how I use Platformtransactiontemplatemanager to manage things:

1. configuration files defined by data sources and things manager

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

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

2. SQL used when testing:

public class Springtransactiontest {
	/**
	 * ready to test 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 high-level JdbcTemplate for Transaction manager testing

/** * Use high-level jdbctemplate for the Thing Manager test */@Test public void Testplatformtransactionmanager () {/** * Defaulttrans Actiondefinition: Transaction definition, defined as isolation level, propagation behavior, etc., in this example, the isolation level is isolation_read_committed (read-committed), * propagation behavior is propagation_
		 REQUIRED (there must be a transaction support, that is, if there is no transaction, create a new transaction, if there is already a transaction, join in the transaction). * Dbctemplate: Perform the corresponding SQL operation through the JdbcTemplate object, and automatically enjoy the transaction support, note that the transaction is thread bound, so the transaction manager can run in a multithreaded environment; * TXMANAGER.COMMIT (status)
		 : Commits the transaction where the status object is bound; * Txmanager.rollback (status): Rolls back the transaction that is bound by the status object when an exception is encountered. * Transactionstatus: Transaction state class, obtained by the transaction definition through the Gettransaction method of the Platformtransactionmanager; When the transaction state is obtained, spring determines based on the propagation behavior.
		How to open a transaction; */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. Test the transaction manager with a low-level solution

/** * 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 use 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 time the database has not been inserted into the data, the original need to submit, thanks to the younger brother reminded, good to others learn} catch (Exception e) {//Because I inserted a lot of this, but never submitted, so the ID increased to 43,  
		      But the result of the submission is the result of the subsequent submission status.setrollbackonly (); 
		Txmanager.rollback (status);
		}finally{datasourceutils.releaseconnection (conn, dataSource); }
	}	

Using Datasourceutils to get and release connections in low-level scenarios, using Txmanager to open management transactions, and for JDBC programming is much more cumbersome and complex than template classes, so this is not recommended


1.2, using transactiontemplate for programming things management

The process of managing things with Platformtransactionmanager is fixed, there are only some logic differences during the management of each thing, and it is possible to consider the combination of template method pattern and callback in the same way as the data access layer of Springde. Encapsulating code that uses Platformtransactionmanager to manage things directly, so that there is a more convenient way to manage things programmatically, that is, to use Transactiontemplate's programmatic management of things. Org.springframework.transaction.support.TransactionTemplate has templated encapsulation of platformtransactionmanager-related things and related exception handling, and developers have more Focus on the corresponding callback interface to provide specific things to define the content can be. Spring provides two callback callback interfaces for Transactiontemplate

Transactioncallback: By implementing the Interface "T dointransaction (transactionstatus status)" method to define the operation code that requires transaction management Transactioncallbackwithoutresult: Inherits the Transactioncallback interface, providing a "void Dointransactionwithoutresult ( Transactionstatus status) "convenience interfaces are used to facilitate transaction operation code that does not require a return value.

Here is the use of the Transactiontemplate template class:

         /**
	 * Using transactiontemplate  template classes to simplify things management, things managed by template class definition
	 * The specific operation is specified by the Transactioncallback interface or the Transactioncallbackwithoutresult callback interface
	 * Every day there are things to manage the code, but by the template class to complete the management of things, 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 with new Transactiontemplate (Txmanager), where the constructor parameter is the Platformtransactionmanager implementation, And the transaction definition is set through its corresponding method, such as transaction isolation level, propagation behavior, etc., the propagation behavior is not specified here, its default is propagation_required;

Transactioncallbackwithoutresult: The implementation of callbacks with no return is used here, and the operations that require transaction management are defined in the Dointransactionwithoutresult method implementation;

Transactiontemplate.execute (): Executes a callback that requires transaction management through this method.


For JTA distributed things I didn't realize here. It feels too much trouble.
Through the above practice, I will basically use Platformtransactionmanager and transactiontemplate for simple transaction, how to apply to the actual project.
I'll do 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.