Convert Sql to Jpql Spring Boot

I'm wondering how to convert this query to JPQL:

SELECT t.id, t.title ,
       (select count(l.id) from topic_like l where t.id = l.topic_id) as countt
from topics t;
4

1 Answer

Subqueries in the select and where clauses will work. You can write the same query as:

select t, (select count(l.id) from TopicLikeJpa l where l.topic.id = t.id)
from TopicJpa t

you can replace select t with select t.id, t.name if you don't want to load the whole entity.

But I think you can rewrite the same query without subqueries as

select t, count(l)
from TopicJpa t
         left join t.topicLikeJpa l
group by t.id

or

select t.id, t.title, count(l)
from TopicJpa t
         left join t.topicLikeJpa l
group by t.id, t.title
6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest