Rim
Rim

Reputation: 1885

Is it better to use JpaRepository or EntityManager in a Spring application?

I have used both approaches, but what's the difference and which is better?

Upvotes: 3

Views: 2505

Answers (2)

Penny Liu
Penny Liu

Reputation: 17498

The choice really depends on your application requirements and developer preference.

In Simple Terms

  • If you need low-level control and flexibility, use EntityManager.

  • If you want high level of abstraction, use JpaRepository.


Use Case

EntityManager

  • Requires low-level control over database operations and custom queries
  • Offers direct access to JPA for working with entities
  • Supports complex queries, including native SQL and stored procedures
  • Suitable for custom requirements that exceed the capabilities of higher-level abstractions

JpaRepository

  • Offers built-in CRUD operations, minimizing code
  • Supports additional features like pagination and sorting
  • Generates queries from method names
  • Allows custom queries with @Query

Upvotes: 0

Ken Chan
Ken Chan

Reputation: 90527

If your query is simple and basic enough such that it can be achieved by Spring data 's query generation feature , use Repository over entity manager will save you some times and effort.

If your query cannot be easily achieved by the query generation feature or you need to fine tune them , use entity manager which gives you the most of the flexibility.

For CRUD only, both of them are more or less the same as entity manager API itself is already clean and simple enough to use.

Upvotes: 3

Related Questions