JPA/Hibernate: 你能在特定的 MapKey 上创建一个连接查询吗?

JPA/Hibernate: Can you create a join query on an specific MapKey?

我想针对一个特定的 MapKey 条目测试一个带有 Map 属性连接的查询,但我还找不到解决方案。有没有人完成过这样的查询并可以分享正确的 JPQL / HQL?

MapKey 列是 enum 类型,值是另一个 @Entity

这是型号:

@Entity
public class Operation {

    @Id
    private int id;

    @OneToMany(mappedBy = "operation", fetch = FetchType.LAZY)
    @Cascade(CascadeType.ALL)
    @MapKeyEnumerated(EnumType.STRING)
    private Map<OperationDetailsType, OperationDetails> operationDetails;
}

@Entity
public class OperationDetails {

    @Id
    private int id;

    private String details;

}

public enum OperationDetailsType { SHORT, FULL }

这是我目前尝试过的查询:

SELECT operation FROM Operation operation join operation.operationDetails['SHORT'] operationDetailsShort WHERE operationDetailsShort.details = :el1

我在 Hibernate 社区中找到了这个参考资料,但是 [...] 的方法会引发错误: https://forum.hibernate.org/viewtopic.php?f=1&t=1004884

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: [ near line 1,...

Hibernate 版本为:4.3.8.Final

谢谢

在改变了网上搜索的方法后,我终于找到了一个可行的解决方案。

重点是使用 JOIN ... ON key() 查询。

这是获取此 JPA 查询的查询语法 运行:

SELECT operation FROM Operation operation
    JOIN operation.operationDetails operationDetailsShort ON key(operationDetailsShort) = 'SHORT'
  WHERE operationDetailsShort.details = :el1

这个构造的好处是您可以针对特定 details 针对 OperationDetails 创建查询:(不用说这是一个高效的解决方案)

SELECT operation FROM Operation operation
    JOIN operation.operationDetails operationDetailsShort ON key(operationDetailsShort) = 'SHORT'
    JOIN operation.operationDetails operationDetailsLong ON key(operationDetailsFull) = 'FULL'
  WHERE operationDetailsShort.details = :el1
    AND operationDetailsFull.details = :el2

编辑:正如 Vlad Mihalcea 提到的,JPQL 等价于休眠 JOIN ... WITHJOIN ... ON。我可以确认这也有效并更新了查询。