2022-05-17

Using sub-select in FROM clause inside JPA @NamedQuery

In my app I need to use @NamedQuery to find the type of the most frequent operation assigned to specific account

@Entity
@Table(name="\"ACCOUNTOPERATION\"")
@NamedQuery(name="AccountOperation.findTypeOfMostFrequentOperation", query="" +
        "SELECT ao.type from AccountOperation ao WHERE ao.account.id = ?1 " +
        "GROUP BY ao.type HAVING COUNT(ao) = (" +
            "SELECT MAX(typeCountQuery.typeCount) " +
            "FROM (" +
                "SELECT COUNT(aop) as typeCount " +
                "FROM AccountOperation aop WHERE aop.account.id = ?1 GROUP BY aop.type" +
            ") as typeCountQuery" +
        ")"
)
public class AccountOperation {

    @ManyToOne
    private Account account;
    private BigDecimal amount;
    private OperationType type;
...

Right after FROM clause at '(' character, which begins typeCountQuery's body I'm getting

')', ',', GROUP, HAVING, IN, WHERE or identifier expected, got '('

I've read that JPA does not support sub-selects in the FROM clause, so is there any way to rewrite SQL code to still use it in @NamedQuery?



No comments:

Post a Comment