0

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?

askedOct 9, 2024 at 15:15
minihulk22's user avatar

1 Answer1

1

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.

answeredOct 9, 2024 at 17:41
Andrey Smelik's user avatar
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@minihulk22 Correlated subqueries in most cases will degrade the performance of your application. You should use a separate query to count the number of entitiesSELECT a_id, COUNT(1) FROM b WHERE a_id IN :ids GROUP BY a_id.

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.