I have a non-Spring application. I want to make an aspect or something like that which should do the code below before and after to make my method or class transactional like Spring’s @Transactional annotation;
Before;
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("AdvancedMapping");
/* Create EntityManager */
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
After;
transaction.commit();
em.close();
How can I do this? Where can I find similar tutorials or examples for it?
EDIT:
By the way, it is needed to have em inside of the method which has @Transactional.
@Transactional
private int doSomething(String text) {
// Here I should have the "em" which was already taken in the aspect,
// so I can persist something in text
SomeEntityObject seo = new SomeEntityObject();
seo.setText(text);
em.persist(seo);
}
2
Answers
Just use AspectJ. You find tutorials and other documentation here. If you build your project with Maven you want to use the AspectJ Maven plugin so as to simplify and automate aspect compilation and weaving.
A little example:
Marker annotation:
Driver application:
Transaction wrapper aspect:
Console log with JPA stuff commented out:
I am adding another answer beside my original one because there seems to be an alternative to rebuilding
@Transactional
from scratch via AspectJ just so as to avoid using the Spring container:Actually, declarative transaction support for Spring already is an AspectJ aspect. The Spring manual describes how to use
@Transactional
with AspectJ without the Spring container. You do not even need Spring XML configuration but can inject the transaction manager directly into the aspect (code snippet quoted from the manual):