The Local Transaction Model | Java Transaction Designe Strategies
The term Local Transacions refers to the face that transaction management is handled by the underlying Database (DBMS) or in the case of JMS the underlying messaging provider. From a developer perspective we do not manage transactions within the Local Transaction Model,but rather connnections.The code example below illustrates the usr of the Local Transaction Model using straight JDBC code:
public void updateTradeOrder(TradeOrderData order) throws Exception { DataSource ds = (DataSource)(new InitialContext()).lookup("jdbc/MasterDs"); Connection con = ds.getConnection(); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String sql = " update trader_order ... "; try { stmt.executeUpdate(sql); } catch (Exception e) { conn.rollback(); throw e; } finally { stmt.close(); conn.close(); } }
Notice in the above example the use of the Connnection.setAutoCommit(false) in conjunction with the Connection.commit() and Connection.rollback() methods. The setAutoCommit() method is a very important part of the overall developer-based connection management.The auto commit flag tells the underlying DBMS whether or not it should commit the connection immediately after the execution of each SQL statement.
For low-level JDBC coding in the Spring Framework you would simply use the
org.springframework.jdbc.datasource.DataSourceUtils as shown in the coding example below:
public void updateTradeOrder(TradeOrderData order) throws Exception { Connection con = DataSourceUtils.getConnection(dataSource); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String sql = " update trader_order ... "; try { stmt.executeUpdate(sql); } catch (Exception e) { conn.rollback(); throw e; } finally { stmt.close(); conn.close(); } }
In Spring, the datasource and corresponding business object would be defined in the Spring configuration file as follows:
<bean id="datasource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/MasterDs"/>
</bean>
<bean>
<property name="dataSource">
<ref local="datasource" />
</property>
</bean>
Auto Commit and Connection Management
浙公网安备 33010602011771号