61

I am using JPA in a website. After exploring about options for saving data, I found 2 approach. The first approach is using an implementation of javax.persistence.EntityManager. I used LocalContainerEntityManagerFactoryBean to instantiate an instance of EntityManager. Once I obtain an instance of an EntityManager, I can use it to save an entity. For example,

entityManager.merge(someEntity);

Another option is to use an instance of org.springframework.data.repository.CrudRepository. One, I obtain an instance of a CrudRepository, I can use it to save an entity. For example,

aCrudRepository.save(someEntity);

What is the difference between using an EntityManager and a CrudRepository to persist an entity into a database ? What are the benefit or disadvantage of the two approach (entity manager vs. crud repository) ?

zfranciscus
  • 16,175
  • 10
  • 47
  • 53

2 Answers2

53

There are several layers of working with persistent data in Java/Spring:

  • JDBC
  • JdbcTemplate
  • JPA (contains EntityManager)
  • Spring Data JPA (contains Repository)

Each abstraction shields developers from lower-level details, but it can bring its own complexities. JdbcTemplate is a thin abstraction over plain JDBC. Repository is an abstraction over EntityManager. It shields developers from some complex details that are introduced with EntityManager and adds boilerplate code and many convenient methods.

For instance, CrudRepository adds the implementation of findAll(), which is so common that it makes sense to predefine it. Repositories have many convenience methods for generating queries from method names (convention over configuration), from the entities themselves (Query By Example). They allow to use nice typesafe Fluent API with Query DSL and or enable dynamic projections.

Jan Bodnar
  • 10,969
  • 6
  • 68
  • 77
  • 1
    so you don't really need the EntityManager, if you are using, for instance, the CrudRepository – user592748 Feb 15 '21 at 05:13
  • @user592748 you do if you need to do something specific that's not easily achievable with the repository methods. e.g. detaching and reattaching in a context – Toni Nagy Jun 06 '23 at 07:34
32

This two interfaces presents two different approaches:

  • org.springframework.data.repository.CrudRepository is common interface for repositories which provide CRUD operations.
  • javax.persistence.EntityManager is associated with a persistence context. Spring has its own interface which extends CrudRepository called JpaRepository for this purposes.

I hope you know about benefits or disadvantages of persistent API. If you don't you can read answers to this question.

Community
  • 1
  • 1
bsiamionau
  • 8,099
  • 4
  • 46
  • 73
  • 2
    Thanks. From this answer, I take it that there is no different between saving an entity using an entity manager or a repository. – zfranciscus Jan 31 '13 at 09:38