Making specific method non transactional in Spring - spring

I have a spring application which is based on Spring Batch. By default spring batch introduces transaction for its steps (i.e. at reader,writer and processor) . There are certain stages where I don't really need transaction to be enabled. Because transaction is enabled unnecessary for these methods its giving me some runtime errors as I am making call to two different databases in one method.
Is there any annotation which spring provides to DISABLE transaction for a specific set of methods ?
OR is there anything available in spring batch which can allow me to get rid of transaction either completely or declarative
I am even open to the solution which can disable transaction globally.
Any link , paper will greatly be appreciated.
Thanks in advance
Samir

Spring Batch is inherently transactional. Even if your datasources are not transactional, the semantics of the JobRepository require it. The closest you can get with Spring Batch and not being transactional is using the ResourcelessTransactionManager. This transaction manager is essentially a no-op transaction manager that just keeps track of if an operation is within the scope of a transaction or not.

Related

How to select PROPAGATION in spring transaction?

I am just reading the spring-mybatis.xml,here are some code of transaction-manager:
I want to know why some methods defines as "REQUIRED" or "SUPPORTS"?How to think about it and decide which to choose?
Your question is, I think it's about Spring transaction and it's depend on your business logic and how you can control spring transaction.
To understand the Spring transaction "REQUIRED" or "SUPPORTS", you need to understand spring transaction definition. This transaction definition types are come from org.springframework.transaction.TransactionDefinition class. But first you need to understand 1)Spring transaction types and then 2)Spring transaction Definition.
1) Spring supports two types of transaction management:
Programmatic transaction management: This means that you have manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
2) Spring Transaction Definition
PROPAGATION_REQUIRED:
Spring REQUIRED behavior means that the same transaction will be used if there is an already opened transaction in the current bean method execution context. Create a new one if none exists.
In short this means that if an inner(2nd Transaction) method causes a transaction to rollback, the outer(1st Transaction) method will fail to commit and will also rollback the transaction.
PROPAGATION_SUPPORTS:
Support a current transaction; execute non-transactionally if none exists.
Understandanding these "REQUIRE" "SUPPORTS" is not enough, as I mentioned to you that you need to understand all Spring definition under org.springframework.transaction.TransactionDefinition class.
Unfortunately, I had one power point about this Spring types and transaction which I wrote at Dec 2014 in slideshare website.
Spring Transaction Management
In this slide, I added very important point about Spring transaction in power point note session. So please not only refer to slide content but also refer to slide note session. Hope it help.
Example, refer as power point notes session too for more understanding about Spring transaction definition.
Edited:
Propagation Means: Typically, all code executed within a transaction scope will run in that transaction. However, you have the option of specifying the behavior in the event that a transactional method is executed when a transaction context already exists. For example, code can continue running in the existing transaction (the common case); or the existing transaction can be suspended and a new transaction created. Spring offers all of the transaction propagation options familiar from EJB CMT. To read about the semantics of transaction propagation in Spring, see Transaction Propagation

What is the point of using spring transaction while we have database level transaction?

What is the point of using spring transaction while we have database level transaction ?
If you use mysql, oracle or any other db in java, they provide methods to make things inside transaction then why spring transaction if I can do transaction using java DB driver methods ?
It's another layer of abstraction over the database transaction API. So if you wanted to use multiple databases with global transactions, Spring would allow you to do this. While I have never done it, I believe it would allow you to use DB2 and Hibernate together, for example.
Generally, what I've found is, if a feature is available in Spring, it's because there is a use case for it. They don't just put things into the framework without a reason.
Also, Spring provides declarative transaction demarcation, which produces more readable and maintainable Java code. The declarative approach lets us change the transaction strategy easily, without changing the code.
The Declarative transaction management approach allows you to manage the transaction with the help of configuration instead of hard coding in your source code. This means that you can separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions
We used Spring AOP along with Hibernate using this transaction strategy Here is an example, Spring AOP transaction mangement with Hibernate.

Is there a better way of detecting if a Spring DB transaction is active than using TransactionSynchronizationManager.isActualTransactionActive()?

I have some legacy code that I am now trying to re-use under Spring. This code is deeply nested in other code so it's not practical to redesign and is called in many situations, only some of which are through Spring. What I'd like to do is to use the Spring transaction if one has been started; otherwise, continue to use the existing (legacy) db connection mechanism. Our first thought was to make our legacy class a bean and use an injected TransactionPlatformManager, but that does not seem to have any methods germane to our situation. Some research showed that Spring has a class called TransactionSynchronizationManager which has a static method isActualTransactionActive(). My testing indicates this method is a reliable way of detecting if a Spring transaction is active:
When called via Spring service without the #Transactional annotation, it returns false
When called via Spring service with #Transactional, it returns true
In my legacy method called the existing way, it returns false
My question: Is there a better way of detecting if a transaction is active?
No better way than the TransactionSynchronizationManager.isActualTransactionActive(). It is the utility method used by spring to handle the transactions. Although it is not advisable to use it within your code, for some specific cases you should - that's why it's public.
Another way might be to use the entity manager / session / connection and check there if there's an existing transaction, but I'd prefer the synchronization manager.

Springs Transaction Management - Understanding Spring Reference, Global/Local, Programmatic/Declarative - Two Questions

Im working with the Spring Framework 3.0.5 and the Hibernate Framework and Im starting to use now Springs Transactionmanagement. I have some questions, just to understand how Springs Transactionmanagement works.
1)
I read this things in the Spring reference:
a) Consistent programming model across different transaction APIs such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO).
b) Spring resolves the disadvantages of global and local transactions. It enables application developers to use a consistent programming model in any environment. You write your code once, and it can benefit from different transaction management strategies in different environments.
c) Gone are the days when the only alternative to using EJB CMT or JTA was to write code with local transactions such as those on JDBC connections, and face a hefty rework if you need that code to run within global, container-managed transactions. With the Spring Framework, only some of the bean definitions in your configuration file, rather than your code, need to change.
From a) I understand that I can use those APIs with Spring without changing the code
From b) I understand that I can use global or local transactions *without changing the code
From c) I understand that while switching between different APIs and global/local transactions I need to change the code
Now I wonder what is correct?
=> Do I need to change the code? When switching between different APIs? When switching between local and global transactions? (Or does it maybe depend on prorgammatic and declarative transaction management?)
2)
I also got an additional question: I really wonder what the use of programmatic transaction management is? Everywhere I read that declarative transactionmanagement is recommended
I read this in spring reference too:
d) With programmatic transaction management, developers work with the Spring Framework transaction abstraction, which can run over any underlying transaction infrastructure. With the preferred declarative model, developers typically write little or no code related to transaction management, and hence do not depend on the Spring Framework transaction API, or any other transaction API.
From d) I understand: with programmatic transaction management I can use any underlying transaction infrastructure... which means what? the different APIs mentioned above?
and: with declarative I do not depend on any api
=> isnt this the same? when I can use any underlying api, I do not depend on any api. I do not really understand this.
where is the difference? I only know that the declarative transaction management is more lightweight, that I have not to start the transaction by my self and catch the exception and handle it and so on. But what is the use of programmatic transaction management then?
Thank you for answering! :-)
You're over-thinking this a bit. The Spring API provides an abstract transaction model that has the same API and semantics regardless of which underlying transaction technology you use. In order to switch from one technology to another, you generally have to alter your Spring config, but the idea is that you never needs to to alter your business logic. So whether you're using local, in-VM JDBC transactions or fully distributed, two-phase-commit XA JPA-style transactions, the API usage within your Spring code is the same. Only the configuration changes.
The difference between declarative and programmatic transaction management is that with the former, you use annotations or XML config to say which bits of code are supposed to be transactional. With programmatic style, you specifically enclose transactional logic using method calls into the Spring API. Note that if you use the declarative style, then Spring will wrap your code in generated logic which uses the programmatic style. The latter is simply a more explicit and low-level version of the former. It gives you more control, but it's more verbose.

spring + struts2, inject DAO into external thread

I have a web application that uses Struts2 + Spring for the resource injection, basically my DAO. Now I would like to create a thread that periodically polls the database and, if needed, send email notifications to users.
I would like to know how I can implement this in a way that this thread can use my DAO. I haven't been able to manage Spring to inject it the way I've done it. So I would like to hear suggestions and see if someone can point me to the right way.
Right now I have a thread started by a ServletContextListener, that just creates a timer and schedules an action every 5 minutes. But I can't get this action to use my DAO. I don't have any need to use this structure, I'm open to using whichever solution works.
Thanks for your help!
Edit: As axtavt suggested, I used Spring task Execution Scheduling and it works perfectly, the thing is that my task gets injected with the DAO but then I get LazyInitializationException every time I try to access a property of my fetched objects, any suggestion on how to solve that??
Perhaps the best option is to use Spring's own scheduling support, see 25. Task Execution and Scheduling (if necessary - with Quartz, see 25.6 Using the OpenSymphony Quartz Scheduler). This apporach allows you to configure your scheduled action as Spring beans, so you can wire them with other beans such as DAO.
Alternatively, you can use the following to obtain any Spring bean in web application (for example, to obtain DAO from your thread):
WebApplicationContextUtils.getWebApplicationContext(servletContext).getBean(...)

Resources