Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/30331767/spring-data-jpa-how-to-get-only-a-list-of-ids-from-findall-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...