How one using spring data specifications can do the equivalent of this:
select a.*, (select count(1) from b where b.a_id = a.id) as countfrom a;
If this is not possible is there an equivalent?
1 Answer1
You can add an additional fieldcount to your entity A, the value of which will be calculated by the correlated subquery:
@Entityclass A { @Id private Long id; @Formula("(select count(1) from b where b.a_id = id)") private Long count;}Then, having created a repository for entity A:
public interface ARepository extends JpaRepository<A, Long> {}You can get the required result usingfindAll() method.
Sign up to request clarification or add additional context in comments.
2 Comments
minihulk22
Thank you so much for your answer! This is indeed what I did while I was waiting for an answer. I'm thrilled this is an accepted solution, as I was not sure about this. Do you see any downside to this?
Andrey Smelik
@minihulk22 Correlated subqueries in most cases will degrade the performance of your application. You should use a separate query to count the number of entities
SELECT a_id, COUNT(1) FROM b WHERE a_id IN :ids GROUP BY a_id.Explore related questions
See similar questions with these tags.