Friday 13 November 2015

Spring Local Declarative Transaction with Spring JDBC


Step-1
Dependency->>>

 <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-jdbc</artifactId>
              <version>${spring.version}</version>

</dependency>


Step-2
define the spring datasource(it is not connection pool)


jdbc.properties
########################################
##########database connection data########
########################################
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/profile_db
username=root

password=root



<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:jdbc.properties</value>
</property>

</bean>

<!-- Creating dataSource manage by spring container which will return connection to us -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />

</bean>

Step-3
Define Spring Jdbc transaction manager
<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <property name="dataSource" ref="dataSource"/>

</bean>


Step-4
associate transactionManager with @Transactional annotation

 <!-- Enabling Spring Transaction with Spring annotation
 @Transactional
   -->
<tx:annotation-driven proxy-target-class="false" transaction-manager="transactionManager"/> 


Step-5
Apply spring transaction inside the java code

@Repository("ProfileDaoImpl")
@Transactional
public class ProfileDaoImpl extends JdbcDaoSupport {

boolean enabled=TransactionSynchronizationManager.isActualTransactionActive();
if(enabled) {
  System.out.println("@_@_@__@_@_@YEAP We are                    using_________*@@@@@@@@@@@@@@");

}
}




No comments:

Post a Comment