2010-09-27

Example: how to start EclipseLink (or other JPA) transaction declaratively in Spring

Here is example of declarative transaction management with EclipseLink JPA provider in Spring-based application. Similar approach should work with other JPA providers as well.
I use Maven for building so these were the required dependencies:


org.eclipse.persistence
javax.persistence
2.0.0


org.aspectj
aspectjrt
1.6.9


org.springframework
spring-aspects
3.0.4.RELEASE



Here is Spring's application context file:



xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">





















Now inside of your.services.package you can have such class:


@Component //instantiate as Spring's bean
public class ProductServiceImpl implements ProductService {
//Trick part #1 - Spring substitutes here entity manager
//and handles it in a way that each thread thinks he's the only one working with this manager.
//For E.M. marked by this annotation declarative transaction management is possible
@PersistenceContext(type = PersistenceContextType.TRANSACTION)
private EntityManager containerEm;

//Trick part #2 - Spring wraps this method in transaction which is handled by containerEm
@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
public void yourMethod() {
...
//Here you can do whatever you want with E.M.:
containerEm.createNativeQuery(...);
//or
em.persist(...);
//etc.
...
}//end of transactional method

}

1 comment:

Prasath Premkumar said...

Are you sure that this configuration will work? i got the following error:
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.1: Element 'tx:annotation-driven' must have no character or element information item [children], because the type's content type is empty.