If you have code similar to this:
public void persistDog(Dog dog) { getJpaTemplate().persist(dog); }
... and if nothing is persisted to database (and you don't see the insert in logs), don't panic. ;)
Enable transactions!
This will do the trick:
import org.springframework.transaction.annotation.Transactional; // ... @Transactional public void persistDog(Dog dog) { getJpaTemplate().persist(dog); } // ...
Your pom.xml file may need this:
... <dependencies> ... <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies> <repositories> ... <repository> <id>r.j.o-groups-public</id> <url>https://repository.jboss.org/nexus/content/groups/public/</url> </repository> </repositories> ...
And your Spring beans file:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" ... <tx:annotation-driven transaction-manager="myTransactionManager" /> <bean id="myTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> ...
Enjoy.
This is not actually a problem of JpaTemplate, but JPA itself. If you use EntityManager directly, the same thing is going to happen (or actually - will not happen at all).
ReplyDeleteBut why are you using JpaTemplate on the first place? It's Javadoc states (in bold!) that you should prefer injecting EntityManger directly, which is both easier and standard way of working with JPA.
Great Article android based projects
DeleteJava Training in Chennai
Project Center in Chennai
Java Training in Chennai
projects for cse
The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training
Hello Tomek, thanks for the comment!
ReplyDeleteWell it says in bold that it exists as a sibling of JdoTemplate and HibernateTemplate, but it doesn't quite say I shouldn't be using it:
http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/orm/jpa/JpaTemplate.html
Or does it? Is there an actual reason for me not to use it?
Is it because NOT using it is less Spring in my code?