How to use subquery in HQL using hibernate

时间:2018-05-14 17:31:24

标签: java hibernate jpa hql

I have a maven project using hibernate and jersey frameworks, i've tried to create a subquery using hql, but its not working, The code on DAO package is the bellow :

...
    StringBuilder str = new StringBuilder();
    str.append(" SELECT t.produtos FROM Tabela t WHERE t.id = :tabelaId ");

    if(parametro != null) { 
        str.append(" AND :parametro like (SELECT p.nome FROM Produto p) ");
    }

    try {
        if(tabelaId != null ) {

            Query query = em.createQuery(str.toString());
            query.setParameter("tabelaId", tabelaId);

            if(parametro != null) {
                query.setParameter("parametro", "%" + parametro + "%");
            }

            produtos = query.setFirstResult(offset).setMaxResults(limit).getResultList();
        }else {
            throw new DAOException("Voce deve informar a tabela!", ErrorCode.BAD_REQUEST.getCode());
        }

    }
...

I receive a error message when i try execute the query.

The error message is:

<AST>:0:0: unexpected AST node: query
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1386)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4316)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2134)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2062)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:813)
at

...

1 个答案:

答案 0 :(得分:1)

这句话:

AND :parametro like (SELECT p.nome FROM Produto p)

不支持JPQL或HQL。支持子查询,但问题是带有子查询的:parametro like