0

I have the following method in my Spring Boot app in my Repository:

@Query("""
            SELECT tw FROM TW tw
            INNER JOIN tw.docks d // TW entity has list of docks
            WHERE d.id = :dockId
            AND tw.status <> 'DELETED'
            """)
List<TW> findAllTWs(long dockId);

How to check if TW has exactly one dock (tw.docks.size() == 1)? I have to filter out tw.docks with more than 1 dock (I want only list of TWs with one dock) Probably I need native query for that

1
  • off the top of my head, I think you basically have 2 options, either check docks.size() in your code or use select count(). If you use select count() and get 1, you'll need a second query to return the record. Commented Oct 20, 2022 at 9:04

2 Answers 2

1

Try with SIZE function which is valid in jpql language.

@Query("""
            SELECT tw FROM TW tw
            INNER JOIN tw.docks d // TW entity has list of docks
            WHERE d.id = :dockId
            AND tw.status <> 'DELETED' AND SIZE(tw.docks) = 1
            """)
Sign up to request clarification or add additional context in comments.

1 Comment

But this solution is better, with tw.docks.size I get WARN: syntax in HQL/JPQL query [tw.ramps.size]; use collection function syntax instead [size(tw.docks)].
1

This should generate sql with a subquery:

SELECT tw 
FROM TW tw 
WHERE tw.docks.size = 1

See the appended documentation, size is a special HQL property.


See: HQL docs

2 Comments

@Matley just a note here docs.oracle.com/cd/E29542_01/apirefs.1111/e13946/… The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however. SIZE is part of JPQL
HQL is only for Hibernate while you might switch to EclipseLink or some other provider in future that comply with the general JPQL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy 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.