加入HQL所需的路径 - Hibernate

时间:2017-10-23 13:47:32

标签: java sql hibernate hql

我有以下HQL

.createQuery("select dl from DocumentLink dl " +
                    "left join DigitalFile df on df.iddigitalfile = dl.parentId and dl.entity.identity =:entityId " +
                    "where (dl.entity.identity =:entityId && dl.parentId =: parentId) || " +
                    "(df.entity.identity =:entityId and df.parentId =: parentId) ", DocumentLink.class);

所需的SQL查询:

select * from documentlink dl
        left join digitalfile df on df.iddigitalfile = dl.ParentId and dl.entity = 261
        where (dl.entity = 5 and dl.parentId = 39845) OR (df.entity = 5 and df.parentId = 39845);

当我在Hibernate环境中运行此查询时,我得到了以下堆栈跟踪。

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [select dl from com.raetsmarine.raetsbase3.domain.DocumentLink dl left join DigitalFile df on df.iddigitalfile = dl.parentId and dl.entity.identity =:entityId where (dl.entity.identity =:entityId and dl.parentId =: parentId)]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91)
    at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:284)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:131)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:93)

你有什么建议我怎样才能以正确的方式转换它?

1 个答案:

答案 0 :(得分:0)

假设有两个类

@Getters
@Setters
public class A {
    Long id;

    @OneToOne
    B b
}

@Getters
@Setters
public class B {
    Long id;
    Long someAttribute;
}

然后加入HQL看起来像

SELECT a FROM A a
LEFT OUTER JOIN a.b
WHERE b.someAttribute = 'Any Value'

请注意,该类的名称已被省略,而且该字段的名称已在HQL中使用,但未实际提供ON clause