Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA. How to get only a list of IDs from findAll() method

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 method 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.

like image 322
tomasz-mer Avatar asked May 19 '15 17:05

tomasz-mer


People also ask

What does the findAll method returns in spring JPA?

The List<Todo> findAll() method returns all Todo objects that are found from the database. The Optional<Todo> findOne(Long id) method finds the todo entry whose id is given as a method parameter.

What is the difference between Findby and findAll in JPA?

No, there is no difference between them, they will execute exactly the same query, the All part is ignored by Spring Data when deriving the query from the method name.

What does findById return in JPA?

Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.

What is the use of @query in JPA?

Understanding the @Query Annotation The @Query annotation can only be used to annotate repository interface methods. The call of the annotated methods will trigger the execution of the statement found in it, and their usage is pretty straightforward. The @Query annotation supports both native SQL and JPQL.


1 Answers

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.

like image 111
eav Avatar answered Sep 20 '22 21:09

eav