jdbctemplate and Affairs
The jdbctemplate operation uses the JDBC default autocommit mode, which means we also
The atomicity of the data operation cannot be guaranteed (either fully or completely invalid), such as:
---------------------------------↓-------------------------------↓-----------------------------------
JdbcTemplate jdbctemplate = new JdbcTemplate (DataSource);
Jdbctemplate.update ("update user SET age = ten WHERE id = ' Erica '");
Jdbctemplate.update ("update user SET age = age+1 WHERE id = ' Erica '");
---------------------------------↑-------------------------------↑-----------------------------------
Since the autocommit mode is used, the first update operation is automatically submitted after the completion, and the database
The record for "Erica" in is already updated, and if the second operation fails, we cannot roll the entire transaction back to the
Initial state. This example may not matter, but for a financial accounting system, such problems will lead
Fatal error.
In order to realize the atomicity of data manipulation, we need to introduce transaction logic into the program, and introduce in JdbcTemplate
Transaction mechanism, there are two ways in spring:
1. Code-controlled transaction management
2. Transaction management for parameterized configuration
Here are two ways to do this.
★ Code-controlled transaction management
First, make the following configuration, assuming the configuration file is (application-context.xml):
---------------------------------↓-------------------------------↓-----------------------------------
<beans>
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource"
destroy-method= "Close" >
<property name= "Driverclassname" >
<value>net.sourceforge.jtds.jdbc.Driver</value>
</property>
<property name= "url" >
<value>jdbc:jtds:sqlserver://127.0.0.1:1433/Sample</value>
</property>
<property name= "username" >
<value>test</value>
</property>
<property name= "Password" >
<value>changeit</value>
</property>
</bean>
<bean id= "TransactionManager"
Class= "Org.springframework.jdbc.datasource.DataSourceTransac
Tionmanager ">
<property name= "DataSource" >
<ref local= "DataSource"/>
</property>
</bean>
<bean id= "Userdao" class= "Net.xiaxin.dao.UserDAO" >
<property name= "DataSource" >
<ref local= "DataSource"/>
</property>
<property name= "TransactionManager" >
<ref local= "TransactionManager"/>
</property>
</bean>
</beans>
---------------------------------↑-------------------------------↑-----------------------------------
Three nodes are included in the configuration:
DataSource
Here we use the DataSource implementation provided by the Apache DHCP component and configure it with
Parameters such as JDBC driver, database URL, username and password.
TransactionManager
For the JDBC DataSource type of data source, we chose the
Datasourcetransactionmanager
As a transaction management component.
If you need to use a container based data source (JNDI), we can use the following configuration:
---------------------------------↓-------------------------------↓-----------------------------------
<bean id= "DataSource"
class= "Org.springframework.jndi.JndiObjectFactoryBean" >
<property name= "Jndiname" >
<value>jdbc/sample</value>
</property>
</bean>
<bean id= "TransactionManager"
Class= "Org.springframework.transaction.jta.JtaTrans
ActionManager "
/>
---------------------------------↑-------------------------------↑-----------------------------------
Userdao declares a Userdao Bean and assigns it a DataSource and
Transactionmanger Resources.
Userdao corresponds to the following code:
---------------------------------↓-------------------------------↓-----------------------------------
public class Userdao {
Private DataSource DataSource;
Private Platformtransactionmanager TransactionManager;
Public Platformtransactionmanager Gettransactionmanager () {
return transactionmanager;
}
public void Settransactionmanager (Platformtransactionmanager
TransactionManager) {
This.transactionmanager = TransactionManager;
}
Public DataSource Executetestsource () {
return DataSource;
}
public void Setdatasource (DataSource DataSource) {
This.datasource = DataSource;
}
public void Insertuser () {
Transactiontemplate tt =
New Transactiontemplate (Gettransactionmanager ());
Tt.execute (New Transactioncallback () {
Public Object dointransaction (transactionstatus status) {
JdbcTemplate JT = new JdbcTemplate (Executetestsource ());
Jt.update (
INSERT into users (username) values (' xiaxin ');
Jt.update (
INSERT into users (Id,username) VALUES (2,
' Erica ');
return null;
}
});
}
}
---------------------------------↑-------------------------------↑-----------------------------------
As you can see, in the Insertuser method, we introduce a new template class:
Org.springframework.transaction.support.TransactionTemplate.
Transactiontemplate encapsulates the functions of transaction management, including transaction rollback when the exception occurs, and the operation becomes
After the work of the transaction submitted. Like JdbcTemplate, it makes it unnecessary for us to try/catch/finally code in trivial
Wandering in. An operation in dointransaction that throws an unhandled exception will be automatically rolled back and, if executed successfully,
will be automatically submitted.
Here we deliberately create some exceptions to see if the database operation is rolled back (by updating from the second statement
The increase ID field intentionally triggers an exception):
Write a simple testcase to observe the actual effect:
---------------------------------↓-------------------------------↓-----------------------------------
InputStream is = new FileInputStream ("Application-context.xml");
Xmlbeanfactory factory = new Xmlbeanfactory (IS);
Userdao Userdao = (Userdao) factory.getbean ("Userdao");
Userdao.insertuser ();
---------------------------------↑-------------------------------↑-----------------------------------
I believe that the above code is somewhat messy, and the writing of the callback class seems to run counter to everyday programming.
Habit (although I think this method is more interesting, because it skillfully solves the author in the early development of data access
Problems that have been encountered in the template).
How to further avoid these problems. Spring's container transaction management mechanism is here to demonstrate its strong
of energy.
★ Parameterized configuration of transaction management
Add a transaction agent (Userdaoproxy) configuration to the application-context.xml above, and
Because transactions are managed by the container, Userdao no longer requires TransactionManager settings to be removed:
---------------------------------↓-------------------------------↓-----------------------------------
<bean id= "Userdaoproxy"
Class= "Org.springframework.transaction.interceptor.Transac
Tionproxyfactorybean ">
<property name= "TransactionManager" >
<ref bean= "TransactionManager"/>
</property>
<property name= "Target" >
<ref local= "Userdao"/>
</property>
<property name= "Transactionattributes" >
<props>
<prop key= "insert*" >PROPAGATION_REQUIRED</prop>
<prop key= "*" >PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id= "Userdao" class= "Net.xiaxin.dao.UserDAO" >
<property name= "DataSource" >
<ref local= "DataSource"/>
</property>
</bean>
---------------------------------↑-------------------------------↑-----------------------------------
In the above configuration, the Userdaoproxy node is configured with a transaction agent for the Userdao Bean (
Target attribute specified).
With the Transactionattributes property, we specify the management policy for the transaction, that is, for all inserts
The first method is transaction management, and if the managed method throws an exception, the transaction in the method is automatically rolled back, if successful
execution, the transaction commits after the method completes. On the other hand, for other methods (represented by the wildcard character *),
Read-only transaction management for better performance.
Accordingly, Userdao.insertuser's code is modified as follows:
---------------------------------↓-------------------------------↓-----------------------------------
public void Insertuser (Registerinfo reginfo) {
JdbcTemplate JT = new JdbcTemplate (Executetestsource ());
Jt.update ("INSERT into users (username) values (' Xiaxin ');");
Jt.update ("INSERT into users (Id,username) VALUES (2, ' Erica ');");
}
---------------------------------↑-------------------------------↑-----------------------------------
The test code is modified as follows:
---------------------------------↓-------------------------------↓-----------------------------------
InputStream is = new FileInputStream ("Application-context.xml");
Xmlbeanfactory factory = new Xmlbeanfactory (IS);
Note that it is necessary to obtain a reference through the proxy bean "Userdaoproxy" instead of the direct Getbean ("Userdao")
In addition there is a potential problem with forced transitions, see hibernate in Spring One
A supplementary description of the compulsory transition.
Userdao Userdao = (Userdao) factory.getbean ("Userdaoproxy");
Userdao.insertuser ();
---------------------------------↑-------------------------------↑-----------------------------------
As you can see, Insertuser has become very concise. Data logic is clearly visible, compared to the previous code-controlled transaction
Management, and the traditional JDBC operation, I believe you will have some quickly cheerful feeling.
Careful readers will say that this simply shifts the code to the configuration file and does not reduce the amount of work. This
The distinction may not be important, and the configuration of transactional management is obviously more advantageous from the standpoint of application maintenance. Moreover, the actual
In the development, if the preliminary design is meticulous, the transaction characteristics of the method will generally not occur after the big changes, and then frequent
In the maintenance process, we only need to face the data logic in the code.
In conjunction with JdbcTemplate, we describe the template operations and transaction management mechanisms in spring. Spring
As an open platform for application development. It also provides good support for other components. In the persistence layer,
Spring provides template implementations for Hibernate, Ibatis, and JDO, as well as the implementation of our development
Provides a strong support. The jdbctemplate operation uses the JDBC default autocommit mode, which means we also
The atomicity of the data operation cannot be guaranteed (either fully or completely invalid), such as:
---------------------------------↓-------------------------------↓-----------------------------------
JdbcTemplate jdbctemplate = new JdbcTemplate (DataSource);
Jdbctemplate.update ("update user SET age = ten WHERE id = ' Erica '");
Jdbctemplate.update ("update user SET age = age+1 WHERE id = ' Erica '");
---------------------------------↑-------------------------------↑-----------------------------------
Since the autocommit mode is used, the first update operation is automatically submitted after the completion, and the database
The record for "Erica" in is already updated, and if the second operation fails, we cannot roll the entire transaction back to the
Initial state. This example may not matter, but for a financial accounting system, such problems will lead
Fatal error.
In order to realize the atomicity of data manipulation, we need to introduce transaction logic into the program, and introduce in JdbcTemplate
Transaction mechanism, there are two ways in spring:
1. Code-controlled transaction management
2. Transaction management for parameterized configuration
Here are two ways to do this.
★ Code-controlled transaction management
First, make the following configuration, assuming the configuration file is (application-context.xml):
---------------------------------↓-------------------------------↓-----------------------------------
<beans>
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource"
destroy-method= "Close" >
<property name= "Driverclassname" >
<value>net.sourceforge.jtds.jdbc.Driver</value>
</property>
<property name= "url" >
<value>jdbc:jtds:sqlserver://127.0.0.1:1433/Sample</value>
</property>
<property name= "username" >
<value>test</value>
</property>
<property name= "Password" >
<value>changeit</value>
</property>
</bean>
<bean id= "TransactionManager"
Class= "Org.springframework.jdbc.datasource.DataSourceTransac
Tionmanager ">
<property name= "DataSource" >
<ref local= "DataSource"/>
</property>
</bean>
<bean id= "Userdao" class= "Net.xiaxin.dao.UserDAO" >
<property name= "DataSource" >
<ref local= "DataSource"/>
</property>
<property name= "TransactionManager" >
<ref local= "TransactionManager"/>
</property>
</bean>
</beans>
---------------------------------↑-------------------------------↑-----------------------------------
Three nodes are included in the configuration:
DataSource
Here we use the DataSource implementation provided by the Apache DHCP component and configure it with
Parameters such as JDBC driver, database URL, username and password.
TransactionManager
For the JDBC DataSource type of data source, we chose the
Datasourcetransactionmanager
As a transaction management component.
If you need to use a container based data source (JNDI), we can use the following configuration:
---------------------------------↓-------------------------------↓-----------------------------------
<bean id= "DataSource"
class= "Org.springframework.jndi.JndiObjectFactoryBean" >
<property name= "Jndiname" >
<value>jdbc/sample</value>
</property>
</bean>
<bean id= "TransactionManager"
Class= "Org.springframework.transaction.jta.JtaTrans
ActionManager "
/>
---------------------------------↑-------------------------------↑-----------------------------------
Userdao declares a Userdao Bean and assigns it a DataSource and
Transactionmanger Resources.
Userdao corresponds to the following code:
---------------------------------↓-------------------------------↓-----------------------------------
public class Userdao {
Private DataSource DataSource;
Private Platformtransactionmanager TransactionManager;
Public Platformtransactionmanager Gettransactionmanager () {
return transactionmanager;
}
public void Settransactionmanager (Platformtransactionmanager
TransactionManager) {
This.transactionmanager = TransactionManager;
}
Public DataSource Executetestsource () {
return DataSource;
}
public void Setdatasource (DataSource DataSource) {
This.datasource = DataSource;
}
public void Insertuser () {
Transactiontemplate tt =
New Transactiontemplate (Gettransactionmanager ());
Tt.execute (New Transactioncallback () {
Public Object dointransaction (transactionstatus status) {
JdbcTemplate JT = new JdbcTemplate (Executetestsource ());
Jt.update (
INSERT into users (username) values (' xiaxin ');
Jt.update (
INSERT into users (Id,username) VALUES (2,
' Erica ');
return null;
}
});
}
}
---------------------------------↑-------------------------------↑-----------------------------------
As you can see, in the Insertuser method, we introduce a new template class:
Org.springframework.transaction.support.TransactionTemplate.
Transactiontemplate encapsulates the functions of transaction management, including transaction rollback when the exception occurs, and the operation becomes
After the work of the transaction submitted. Like JdbcTemplate, it makes it unnecessary for us to try/catch/finally code in trivial
Wandering in. An operation in dointransaction that throws an unhandled exception will be automatically rolled back and, if executed successfully,
will be automatically submitted.
Here we deliberately create some exceptions to see if the database operation is rolled back (by updating from the second statement
The increase ID field intentionally triggers an exception):
Write a simple testcase to observe the actual effect:
---------------------------------↓-------------------------------↓-----------------------------------
InputStream is = new FileInputStream ("Application-context.xml");
Xmlbeanfactory factory = new Xmlbeanfactory (IS);
Userdao Userdao = (Userdao) factory.getbean ("Userdao");
Userdao.insertuser ();
---------------------------------↑-------------------------------↑-----------------------------------
I believe that the above code is somewhat messy, and the writing of the callback class seems to run counter to everyday programming.
Habit (although I think this method is more interesting, because it skillfully solves the author in the early development of data access
Problems that have been encountered in the template).
How to further avoid these problems. Spring's container transaction management mechanism is here to demonstrate its strong
of energy.
★ Parameterized configuration of transaction management
Add a transaction agent (Userdaoproxy) configuration to the application-context.xml above, and
Because transactions are managed by the container, Userdao no longer requires TransactionManager settings to be removed:
---------------------------------↓-------------------------------↓-----------------------------------
<bean id= "Userdaoproxy"
Class= "Org.springframework.transaction.interceptor.Transac
Tionproxyfactorybean ">
<property name= "TransactionManager" >
<ref bean= "TransactionManager"/>
</property>
<property name= "Target" >
<ref local= "Userdao"/>
</property>
<property name= "Transactionattributes" >
<props>
<prop key= "insert*" >PROPAGATION_REQUIRED</prop>
<prop key= "*" >PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id= "Userdao" class= "Net.xiaxin.dao.UserDAO" >
<property name= "DataSource" >
<ref local= "DataSource"/>
</property>
</bean>
---------------------------------↑-------------------------------↑-----------------------------------
In the above configuration, the Userdaoproxy node is configured with a transaction agent for the Userdao Bean (
Target attribute specified).
With the Transactionattributes property, we specify the management policy for the transaction, that is, for all inserts
The first method is transaction management, and if the managed method throws an exception, the transaction in the method is automatically rolled back, if successful
execution, the transaction commits after the method completes. On the other hand, for other methods (represented by the wildcard character *),
Read-only transaction management for better performance.
Accordingly, Userdao.insertuser's code is modified as follows:
---------------------------------↓-------------------------------↓-----------------------------------
public void Insertuser (Registerinfo reginfo) {
JdbcTemplate JT = new JdbcTemplate (Executetestsource ());
Jt.update ("INSERT into users (username) values (' Xiaxin ');");
Jt.update ("INSERT into users (Id,username) VALUES (2, ' Erica ');");
}
---------------------------------↑-------------------------------↑-----------------------------------
The test code is modified as follows:
---------------------------------↓-------------------------------↓-----------------------------------
InputStream is = new FileInputStream ("Application-context.xml");
Xmlbeanfactory factory = new Xmlbeanfactory (IS);
Note that it is necessary to obtain a reference through the proxy bean "Userdaoproxy" instead of the direct Getbean ("Userdao")
In addition there is a potential problem with forced transitions, see hibernate in Spring One
A supplementary description of the compulsory transition.
Userdao Userdao = (Userdao) factory.getbean ("Userdaoproxy");
Userdao.insertuser ();
---------------------------------↑-------------------------------↑-----------------------------------
As you can see, Insertuser has become very concise. Data logic is clearly visible, compared to the previous code-controlled transaction
Management, and the traditional JDBC operation, I believe you will have some quickly cheerful feeling.
Careful readers will say that this simply shifts the code to the configuration file and does not reduce the amount of work. This
The distinction may not be important, and the configuration of transactional management is obviously more advantageous from the standpoint of application maintenance. Moreover, the actual
In the development, if the preliminary design is meticulous, the transaction characteristics of the method will generally not occur after the big changes, and then frequent
In the maintenance process, we only need to face the data logic in the code.
In conjunction with JdbcTemplate, we describe the template operations and transaction management mechanisms in spring. Spring
As an open platform for application development. It also provides good support for other components. In the persistence layer,
Spring provides template implementations for Hibernate, Ibatis, and JDO, as well as the implementation of our development
Provides a strong support.