Need Example Transaction handling in Spring 3 - spring

I need step by step guide to handle transactions in spring sqltemplate. Transaction handling has to be implemented in my project. Guide me. Need to use the transaction Managment with SqlTemplate.

I suggest you use #Transaction annotation than code it manually. You may follow example here. For its best practice, you may read here. If you plan to spend few hours to study Spring Data JPA, you almost no need to handle transaction manually for most cases.
Thanks.

if you are using Programmatic Transactions then use below
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="dataSource"/>
</property>
</bean>
Programmatic means you have transaction management code surrounding your business code.
This gives extreme flexibility, but is difficult to maintain.
Declarative means you separate transaction management from the business code.
You can use annotations or XML based configuration.
Declarative Transaction Management allows to eliminate any dependencies on the transaction framework from the Java code.
The four participants to provide the transaction support are transaction manager, proxy factory, transaction interceptor, and a set of transaction attributes. below is an example
<bean id="boxOffice" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref bean="transactionManager"/></property>
<property name="target">
<ref bean="boxOfficeService"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="get*">PROPAGATION_SUPPORTS,readOnly</prop>
<prop key="allocate*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>

Related

Spring + JMS + ActiveMQ without dependency on ActiveMQ

I'm trying to build a MQ producer that sends a message to an ActiveMQ queue. The thing is that I don't want the implementation to be specific for ActiveMQ. I actually am doing the ActiveMQ sending in dev environment, and in production the application server will use something else. I'm planning to use Maven to create 2 profiles that will filter resources based on the given profile.
I started playing with JNDI, but I'm stuck... I tried a lot of options, but none are viable.
For now, my spring config xml is like this:
<jee:jndi-lookup id="mqConnectionFactory" jndi-name="java:comp/env/jms/mqConnectionFactory" />
<bean id="jmsJndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</prop>
<prop key="java.naming.provider.url">vm://localhost</prop>
</props>
</property>
</bean>
<bean id="ismeJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="defaultDestination" ref="ismeJmsDestination"/>
<property name="connectionFactory" ref="mqConnectionFactory"/>
</bean>
<bean id="ismeJmsDestination" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jmsJndiTemplate"/>
<property name="jndiName" value="dynamicQueues/FOO.BAR"/>
</bean>
mqConnectionFactory cannot be found because I didn't add it in JNDI. I don't know how to add it actually, as this is not a webapp, so no context.xml.
Can someone help me in the right direction?
Whatever broker implementation you chose, you need to have the corresponding client library in your classpath. The JMS API is just an API, you need an actual implementation to connect to the broker of your choice.
Say you want to connect to ActiveMQ in development and to whatever JMS implementation in production. You can isolate those two config in separate profiles and make the activeMQ dependency an optional dependency in Maven.

persistence.xml in a Spring application

I'm used to have persistence.xml in my projects in which I define the provider to use (hibernate in most cases).
However, I'm starting a new project in which it is mandatory to use Spring framework. I've seen some blogs describing the integration of Hibernate in Spring and I've understood that I should declare a session factory in spring's beans descriptor org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
All the examples I've seen don't mention the use of persistence.xml, persistence context, entity manager...
I'm not sure I understand this point, I always thought that Hibernate is just a provider of JPA unless the factory declared in application-context.xml is doing something in background. If it is the case, I would like to understand how it is working..
thanks in advance...
AnnotationSessionFactoryBean is Factory bean implemented by Spring to create Hibernate Session Factory and shared to Spring's Application Context.if you are planning to use Direct Hibernate ( in case you dont need persistent.xml / per-cont.xml / entityManager) you can provide the properties in AnnotationSession FactoryBean. and can be injected in Any DAO.
How ever if you are planing to wire through JPA. Then you need ( persistent and persistent-context and entity Manager). In order to do that you required three steps
1. declare / configure Spring's JPA Adapter to create EntityManager instance for you
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
Inside JPA Bean declaration provide details about your database and who is ORM provider such as ( hibernate /toplink / ....) in your case Hibernate
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.Oracle9Dialect"/>
</bean>
</property>
then Provide information about your persistent entity details in persistent.xml or some way
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
if you have any specific JPA properties then
<property name="jpaProperties">
<props>
<!-- <prop key="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</prop>
-->
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.use_sql_comments">false</prop>
</props>
</property>
Bottom line, Spring provies adapters to directly to Hibernate ( in that case your dont need Jpa files such as persistent.xml and so but you need hibernate related files like hbm files) or adapters to the JPA ( in that case you have provide details about who is JPA vendor and instrut spring how to connect to the JPA vendor).
Hope the above clarifies.

How to apply transactions best practice for read operations in Spring MVC using Hibernate?

As it is mentioned in blogs/books (e.g. Java Transactions Design Strategies by Mark Richards), read operations must have the Propagation.SUPPORTS attribute.
In a simple Spring 3.1 MVC project with Hibernate 4.1 the scenario is:
Declarative transaction management using #Transactional
sessionFactory of org.springframework.orm.hibernate4.LocalSessionFactoryBean
Transaction manager of org.springframework.orm.hibernate4.HibernateTransactionManager
Service class with #Transactional(propagation=Propagation.REQUIRED)
Function of that Service class that only retrieves a resultset (performs read operation) with #Transactional(propagation=Propagation.SUPPORTS)
Function of read operation retieves the resultset using sessionFactory.getCurrentSession().get()
Of course, when a Controller executes the function of read operation, the exception "No Session found for current thread" is raised because a transaction is not started and a session is not obtained.
Based on the above configuration (while it is best e.g. non-invasive, less code etc) the Propagation.SUPPORTS attribute cannot be used unless a transaction is started before with Propagation.REQUIRED or Propagation.REQUIRES_NEW.
How do we use use Propagation.SUPPORTS for read operations without having to start a transaction e.g. with Propagation.REQUIRED before but still taking advantage the benefits of declarative transaction management?
Thank you in advance.
Coder, here is the configuration:
<tx:annotation-driven transaction-manager="txManager"/>
<context:component-scan base-package="com.myapps.service.impl" />
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driverClassName}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>.....</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
I disagree with using SUPPORTS for read operations. Use REQUIRED.
A transaction is needed anyway to perform every database operation
Doing several small transactions to read several things at once won't benefit from the first-level cache
There won't be any isolation between all the subsequent reads, meaning that something not visible to the first read might become visible for the second one
you'll get lazy loading exceptions when traversing associations
Transaction is not always required for Propagation.SUPPORTS.
Propagation.SUPPORTS: Support a current transaction, execute non-transactionally if none exists.

Nested Spring TxProxyTemplate issue

I have the following config.
<bean id="abcManager" parent="TxProxyTemplate">
<property name="target">
<bean class="com.x.y.AbcManagerImpl">
<property name="abcDAO" ref="abcDAO"/>
<property name="xyzManager" ref="xyzManager"/>
</bean>
</property>
</bean>
<bean id="xyzManager" parent="TxProxyTemplate">
<property name="target">
<bean class="com.x.y.XyzManagerImpl">
<property name="abcDAO" ref="abcDAO"/>
<property name="anotherManager" ref="anotherManager"/>
</bean>
</property>
</bean>
<bean id="anotherManager" parent="TxProxyTemplate">
<property name="target">
<bean class="com.x.y.AnotherManagerImpl">
<property name="abcDAO" ref="abcDAO"/>
<property name="oneMoreManager" ref="oneMoreManager"/>
</bean>
</property>
</bean>
What is the issue with the following configuration? will having the same DAO at the different levels cause concurency issues?
We found that we get lots of weblogic connection releases when we have high load.
How is this related to the connection release issue?
We use Hibernate for DAO operations.
First, analyse the logs to see when spring creates and closes transactions.
Set the logger for org.springframework.transaction to DEBUG for this.
Next my guess is you need to examine your #Transactional annotations (which I assume you use on your managers (=services?). Make sure the propagation is set correctly because this might be related to your issue (hard to say without seeing your manager's code of course).
To answer your question directly:
What is the issue with the following configuration? will having the same DAO at the different levels cause concurency issues?
Nothing, and no. I don't see anything wrong with this. Not sure what you mean about 'same DAO' - you don't have the same DAO. You have the same parent, but 3 distinct DAOs.
If you're asking, then, why is weblogic closing your DB connections before your transaction completes, we wouldn't be able to answer that with the information above.

Spring IntTest is getting "Failed to grow the connection pool" from Atomikos

I have a Spring application that normally runs fine in WebLogic.
I have a set of integration tests that use the Atomikos "Transaction Essentials" framework to provide the standalone transaction manager. I had this working, but I'm now seeing a new problem, but I don't know what I might have changed that would make this happen.
I'm seeing a stack trace beginning like this:
org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.atomikos.jdbc.AtomikosSQLException: Failed to grow the connection pool
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
Here are the relevant bean definitions:
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
init-method="init" destroy-method="close">
<!-- when close is called, should we force transactions to terminate or not? -->
<property name="forceShutdown">
<value>true</value>
</property>
</bean>
<!-- Also use Atomikos UserTransactionImp, needed to configure Spring -->
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">
<property name="transactionTimeout">
<value>300</value>
</property>
</bean>
<!-- Configure the Spring framework to use JTA transactions from Atomikos -->
<bean id="catalogTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<ref bean="atomikosTransactionManager" />
</property>
<property name="userTransaction">
<ref bean="atomikosUserTransaction" />
</property>
</bean>
I also have several like this:
<bean id="appConfigDataSource"
class="com.atomikos.jdbc.AtomikosDataSourceBean"
p:uniqueResourceName="appConfigDataSource"
p:xaDataSourceClassName="oracle.jdbc.xa.client.OracleXADataSource"
p:poolSize="5">
<property name="xaProperties">
<props>
<prop key="user">${ds.appconfig.userName}</prop>
<prop key="password">${ds.appconfig.password}</prop>
<prop key="URL">${ds.appconfig.url}</prop>
</props>
</property>
</bean>
I tried changing the "5" to "50". This makes it run longer, but it still fails with the same error. There's no way that it would even need 5 or even 50 connections. I have a strong feeling that if I changed it to a larger number, it would run even longer, and still fail with the same error.
What might I be missing?
Never mind. It was a simple problem. I forgot that the hostname of my test database changed a while ago, and I forgot to change the property value.

Resources