Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Spring JpaRepository custom-implementations automatically transactional?

everything is in the title...

I have a repository extending JpaRepository<User, Long> with additional customized methods, following the pattern described in http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/jpa.repositories.html

The Spring documentation says: CRUD methods on repository instances are transactional by default. For reading operations the transaction configuration readOnly flag is set to true, all others are configured with a plain @Transactional.

  • Does this applies to the custom-methods? Are there transactional?
  • Advanced: Where could I find the answer by myself? (i.e. which class of Spring framework is responsible for generating the dynamic-proxy and decorating the calls?)

Thank you in advance!

like image 305
jeromerg Avatar asked Nov 01 '22 01:11

jeromerg


1 Answers

1) Same as Ralphs answer. They have to be annotated with @Transaction or handled by you explicitly

2) There is no "responsible" class for extending/decorating the Spring repository interfaces. YOU are the one responsible for extending them.

I'm going to add an example of a custom method that executes a custom query.

PersonRepository

public interface PostRepository extends CrudRepository<Post, Long>{
    List<Post> getPostsOlderThanDate(Date date);
}

PersonRepositoryImpl

import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.Date;
import java.util.List;

public class PostRepositoryImpl extends SimpleJpaRepository<Post, Long> implements PostRepository {

    private EntityManager entityManager;

    public PostRepositoryImpl(EntityManager em) {
        super(Post.class, em);
        this.entityManager = em;
    }

    @Transactional
    @Override
    public List<Post> getPostsOlderThanDate(Date date) {
        String query = ""; //create query
        TypedQuery<Post> typedQuery = entityManager.createQuery(query, Post.class);
        return typedQuery.getResultList();
    }
}

You then create your EntityManagerFactory bean (which you build with a Hibernate persistance provider, or however you set it up, it's up to you), and inject it into the constructor of the PersonRepositoryImpl bean.

<bean id="personRepository" class="com.package.PersonRepositoryImpl">
    <constructor-arg ref="entityManagerFactory" />
</bean>

These would be the steps to provide some custom queries into your database.

NOTE: if you need help setting up your EntityManager just leave a comment addressed to me and I'll give you the spring config and dependencies.

like image 138
Gabriel Ruiu Avatar answered Nov 11 '22 13:11

Gabriel Ruiu