Reputation: 1109
It seems to me that Spring Data JPA was created primarily to allow easy query creation with query generation by method name. However, I need to create complex queries, and I cannot take advantage of the query generator. As such, I'm stuck with calling findAll() on a Specification that behind the scenes is using plain JPA criteria to build my query. Seems like I might as well drop Spring Data, then?
Are there any other technical benefits from Spring Data besides automated query generation that I couldn't get if I used, for example, Spring Boot with JPA?
(P.S. - I cannot directly use JPQL because my queries are dynamically created and must be type-safe)
Upvotes: 2
Views: 1536
Reputation: 9319
Two more points from my side
The abstraction provided from Spring Data JPA allows persistence layer to be changed from one relational model to another, without any boilerplate code and huge refactorings.
Query lookup strategies , validation of @Query annotated queries at bootstrap time, so that if the repository infrastructure does not find a declared query for the method at bootstrap time, it fails.
As mentioned above, the huge benefit is that you have all CRUD operations built-in, via single access point, in addition you are able to implement custom repositories for your complex queries using either QueryDSL or Specifications - so you have type safe queries as you said. And again, at then end you have single access point of all your DAO methods, via single interface.
P.S. QueryDSL is more type safe compared to criterias, more compact, similiar to JPQL syntax and easier to use.
Upvotes: 2
Reputation: 24527
Yes, of course there are other benefits!
All "basic" queries are already implemented, i.e. findById, save, delete
Pagination works out of the box. You can pass a Pageable
Object simply from Controller to Service to you Repository and it just works! (including sorting)
Using Spring's Specification
API is a little bit more simple than plain JPA stuff, because you just create Predicates and don't have to mess around with EntityManager
and PersistenceContext
.
And when using Java8 it gets really nice!
public class MySpecification {
public static Specification<MyEntity> isDeleted() {
return (root, query, cb) -> {
return cb.isTrue(root.get(MyEntity_.deleted));
};
}
}
And then use it:
@Autowired
private MyEntityRepo repo;
public void test() {
repo.findAll(Specifications.where(MySpecification.isDeleted()));
}
An Alternative might be to use QueryDSL. It's not as flexible as JPA Criteria when using Spring Data Repositories, but those queries look super sexy!
public void test() {
QMyEntity myEntity = QMyEntity.myEntity;
repo.findAll(myEntity.deleted.eq(true));
}
Upvotes: 4