Spring

Transaction management under J2EE 1.2

posted on 07 Jan 2009 09:10 by sonicneo  in Spring
A transaction can be defined as an indivisible unit of work comprised of several operations, all or none of which must be performed in order to preserve data integrity. For example, a transfer of 00 from your checking account to your savings account would consist of two steps: debiting your checking account by 00 and crediting your savings account with 00. To protect data integrity and consistency -- and the interests of the bank and the customer -- these two operations must be applied together or not at all. Thus, they constitute a transaction. 

Properties of a transaction

All transactions share these properties: atomicity, consistency, isolation, and durability (represented by the acronym ACID). 

  • Atomicity: This implies indivisibility; any indivisible operation (one which will either complete fully or not at all) is said to be atomic.
  • Consistency: A transaction must transition persistent data from one consistent state to another. If a failure occurs during processing, the data must be restored to the state it was in prior to the transaction.
  • Isolation: Transactions should not affect each other. A transaction in progress, not yet committed or rolled back (these terms are explained at the end of this section), must be isolated from other transactions. Although several transactions may run concurrently, it should appear to each that all the others completed before or after it; all such concurrent transactions must effectively end in sequential order.
  • Durability: Once a transaction has successfully committed, state changes committed by that transaction must be durable and persistent, despite any failures that occur afterwards.


A transaction can thus end in two ways: a commit, the successful execution of each step in the transaction, or a rollback, which guarantees that none of the steps are executed due to an error in one of those steps.

Transaction isolation levels

The isolation level measures concurrent transactions' capacity to view data that have been updated, but not yet committed, by another transaction. If other transactions were allowed to read data that are as-yet uncommitted, those transactions could end up with inconsistent data were the transaction to roll back, or end up waiting unnecessarily were the transaction to commit successfully. 

A higher isolation level means less concurrence and a greater likelihood of performance bottlenecks, but also a decreased chance of reading inconsistent data. A good rule of thumb is to use the highest isolation level that yields an acceptable performance level. The following are common isolation levels, arranged from lowest to highest:

  • ReadUncommitted: Data that have been updated but not yet committed by a transaction may be read by other transactions.
  • ReadCommitted: Only data that have been committed by a transaction can be read by other transactions.
  • RepeatableRead: Only data that have been committed by a transaction can be read by other transactions, and multiple reads will yield the same result as long as the data have not been committed.
  • Serializable: This, the highest possible isolation level, ensures a transaction's exclusive read-write access to data. It includes the conditions of ReadCommitted and RepeatableRead and stipulates that all transactions run serially to achieve maximum data integrity. This yields the slowest performance and least concurrency. The term serializable in this context is absolutely unrelated to Java's object-serialization mechanism and the java.io.Serializable interface.


Transaction support under J2EE

The Java 2 Enterprise Edition (J2EE) platform consists of the specification, compatibility test suite, application-development blueprints, and reference implementation. Numerous vendors provide application servers/implementations based on the same specification. J2EE components are meant to be specification-centric rather than product-centric (they are built to a specification, rather than around a particular application-server product). J2EE applications include components that avail of the infrastructural services provided by the J2EE container and server, and therefore need to focus only on "business logic." J2EE supports flexible deployment and customization in the target production environment, using declarative attributes provided by a deployment descriptor. J2EE aims to protect IT efforts and reduce application-development costs. J2EE components may be built in-house or procured from outside agencies, which can result in flexibility and cost benefits for your IT department. 

Transaction support is an important infrastructural service offered by the J2EE platform. The specification describes the Java Transaction API (JTA), whose major interfaces include javax.transaction.UserTransaction and javax.transaction.TransactionManager. The UserTransaction is exposed to application components, while the underlying interaction between the J2EE server and the JTA TransactionManager is transparent to the application components. The TransactionManager implementation supports the server's control of (container-demarcated) transaction boundaries. The JTA UserTransaction and JDBC's transactional support are both available to J2EE application components.

more

XA transactions using Spring

posted on 07 Jan 2009 09:09 by sonicneo  in Spring

Using J(2)EE application server has been a norm when high-end features like transactions, security, availability, and scalability are mandatory. There are very few options for java applications, which require only a subset of these enterprise features and, more often than not, organizations go for a full-blown J(2)EE server. This article focuses on distributed transactions using the JTA (Java Transaction API) and will elaborate on how distributed transactions (also called XA) can be used in a standalone java application, without a JEE server, using the widely popular Spring framework and the open source JTA implementations of JBossTS, Atomikos and Bitronix.

Distributed transaction processing systems are designed to facilitate transactions that span heterogeneous, transaction-aware resources in a distributed environment. Using distributed transactions, an application can accomplish tasks such as retrieving a message from a message queue and updating one or more databases in a single transactional unit adhering to the ACID (Atomicity, Consistency, Isolation and Durability) criteria. This article outlines some of the use cases where distributed transactions (XA) could be used and how an application can achieve transactional processing using JTA along with the best of the breed technologies. The main focus is on using Spring as a server framework and how one can integrate various JTA implementations seamlessly for enterprise level distributed transactions.

XA Transactions and the JTA API

Since the scope of the article is limited to using JTA implementations using the Spring framework, we will briefly touch upon the architectural concepts of distributed transaction processing.

XA Transactions

The X/Open Distributed Transaction Processing, designed by Open Group(a vendor consortium), defines a standard communication architecture that allows multiple applications to share resources provided by multiple resource managers, and allows their work to be coordinated into global transactions. The XA interfaces enable the resource managers to join transactions, to perform 2PC (two phase commit) and to recover in-doubt transactions following a failure.

Figure 1: Conceptual model of the DTP environment.

Figure 1: Conceptual model of the DTP environment.

As shown in Figure 1, the model has the following interfaces:

  1. The interface between the application and the resource manager allows an application to call a resource manager directly, using the resource manager's native API or native XA API depending on if the transaction needs to be managed by the transaction monitor or not.

  2. The interface between the application and the transaction monitor (TX interface), lets the application call the transaction monitor for all transaction needs like starting a transaction, ending a transaction, rollback of a transaction etc.

  3. The interface between the transaction monitor and the resource manager is the XA interface. This is the interface, which facilitates the two-phase commit protocol to achieve distributed transactions under one global transaction.

  4.  

    more

edit @ 7 Jan 2009 09:09:41 by sonicneo

Spring ApplicationContext within Servlet

posted on 03 Dec 2008 09:59 by sonicneo  in Spring

ถ้าต้องการจะจัดการกับ Bean ของ  Spring ซึ่งอยู่ใน Servlet Controller และไม่รู้ว่าจะ implementation ApplicationContext อย่างไร   วันนี้มาแนะนำการใช้ XmlWebApplicationContext ซึ่งง่ายมากๆเขียนแค่ 4 บรรทัด  

XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setServletContext(getServletContext());
ctx.setConfigLocations(new String[] { beans definition locations });
ctx.refresh();

 

Beans definition location จะต้องเป็น relative path เช่น  WEB-INF/META-INF/services/descriptor.xml

และสุดท้ายอย่าลืมเรียนก method refresh() ด้วยนะครับ

การจัดการ transaction ด้วย spring

posted on 03 Dec 2008 09:17 by sonicneo  in Spring

ก่อนอื่นก็ต้องมา config ที่ไฟล์ xml ซะก่อนนะ  ต่อไปนี้เป็นการกำหนด trasaction สำหรับ Hibernate นะครับ

เริ่มแรกก็ประกาศบีนชื่อ  hibernateTxManager ซึ่งเป็นคลาส HibernateTransactionManager จากนั้นก็ injection sessionFactory เข้าไปด้วย

 จากนั้นประจุดตัดเพื่อบอกให้รู้ว่าต้องการทำ trasaction ที่ service อะไร  ในที่นี้สามารถกำหนดได้ว่าให้เลือกที่
ทั้ง package โดยเีขียนไว้ใน tag aop:config

จากนั้นเป็นการกำหนดว่าต้องการให้ method ที่ชื่อขึ้นต้นด้วยอะไรบ้างที่จะทำ trasaction โดยเขียนไว้ใน

tag tx:advice

เพียงเท่านี้เราก็สามารถกำหนดการทำ trasaction ด้วย Spring  โดยที่เราไม่ต้องเขียน Code เพื่อจัดการ trasaction เองเลย  ที่เหลือเราก็เพียงแค่เขียนคลาสธรรมดา  ปล่อยให้เป็นหน้าที่ของ Spring เป็นคนจัดการแทนเรา

 

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

    <!-- SessionFactory, DataSource, etc. omitted -->
    <bean id="hibernateTxManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <aop:config>
        <aop:pointcut id="hibernateUrCmitServiceMethods"
            expression="execution(* com.ais.itams.ur.cmit.spring.hibernate.persistance.service.*.*(..))" />
        <aop:advisor advice-ref="txAdviceHibernate" pointcut-ref="hibernateUrCmitServiceMethods" />
    </aop:config>

   
    <tx:advice id="txAdviceHibernate" transaction-manager="hibernateTxManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" read-only="false" />
            <tx:method name="update*" propagation="REQUIRED" read-only="false" />
            <tx:method name="delete*" propagation="REQUIRED" read-only="false" />
            <tx:method name="*" read-only="true" />
        </tx:attributes>
    </tx:advice>
</beans>

edit @ 3 Dec 2008 09:35:39 by sonicneo

Config DataSource in Spring

posted on 13 Nov 2008 18:18 by sonicneo  in Spring

ตัวอย่างการใช้ DBCP

 

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName"><value>${db.driver}</value></property>
        <property name="url"><value>${db.url}</value></property>
        <property name="username"><value>${db.user}</value></property>
        <property name="password"><value>${db.password}</value></property>
        <property name="poolPreparedStatements"><value>true</value></property>
        <property name="maxActive"><value>10</value></property>
        <property name="maxIdle"><value>10</value></property>
</bean>                                   

 

ตัวอย่างการใช้  C3P0

 

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass">
            <value>net.sourceforge.jtds.jdbc.Driver</value>
        </property>
        <property name="jdbcUrl">
               <value>jdbc:jtds:sqlserver://${database.host}:${database.port}/${database.name};ssl=request</value>
        </property>
        <property name="user">
            <value>${database.username}</value>
        </property>
        <property name="password">
            <value>${database.password}</value>
        </property>
        <property name="acquireIncrement">
            <value>3</value>
        </property>
        <property name="minPoolSize">
            <value>1</value>
        </property>
        <property name="maxPoolSize">
            <value>15</value>
        </property>
        <property name="maxStatementsPerConnection">
            <value>100</value>
        </property>
        <property name="automaticTestTable">
            <value>c3p0_test_table</value>
        </property>
        <property name="numHelperThreads">
            <value>20</value>
        </property>
    </bean>