2010-06-24

When Spring's jpaTemplate persist does not save

Just a quick one...

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.

2 comments:

  1. 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).

    But 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.

    ReplyDelete
  2. Hello Tomek, thanks for the comment!
    Well 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?

    ReplyDelete