I have a very complicated model. Entity has a lot relationship and so on.
I try to use Spring Data JPA and I prepared a repository.
but when I invoke a metod findAll() with specification for the object a have a performance issue because objects are very big. I know that because when I invoke a method like this:
@Query(value = "select id, name from Customer ")
List<Object[]> myFindCustomerIds();
I didn't have any problems with performance.
But when I invoke
List<Customer> findAll();
I had a big problem with performance.
The problem is that I need to invoke findAll method with Specifications for Customer that is why I cannot use method which returns a list of arrays of objects.
How to write a method to finding all customers with specifications for Customer entity but which returns only an IDs.
like this:
List<Long> findAll(Specification<Customer> spec);
- I cannot use in this case pagination.
Please help.
This is now supported by Spring Data using Projections:
Than in your
Customer
repositoryEDIT:
As noted by Radouane ROUFID Projections with Specifications currently doesn't work beacuse of bug.
But you can use specification-with-projection library which workarounds this Spring Data Jpa deficiency.
Unfortunately Projections does not work with specifications.
JpaSpecificationExecutor
return only a List typed with the aggregated root managed by the repository (List<T> findAll(Specification<T> var1);
)An actual workaround is to use Tuple. Example :
where
Projections
is a functional interface for root projection.SingleTupleMapper
andTupleMapper
are used to map theTupleQuery
result to the Object you want to return.Example of use :
I hope it helps.
Why not using the
@Query
annotation?@Query("select p.id from #{#entityName} p") List<Long> getAllIds();
The only disadvantage I see is when the attribute
id
changes, but since this is a very common name and unlikely to change (id = primary key), this should be ok.I solved the problem.
(As a result we will have a sparse Customer object only with id and name)
Define their own repository:
And an implementation (remember about suffix - Impl as default)