【问题标题】:"org.hibernate.QueryException: duplicate association path" Error (May need to include table twice)“org.hibernate.QueryException:重复关联路径”错误(可能需要包含两次表)
【发布时间】:2018-09-16 22:55:51
【问题描述】:

我正在使用 Hibernate 来实现一个搜索页面,其中可能使用或不使用不同的条件。一个标准是SpecialTable 中的ID。另一个标准是"Or"MainTableSpecialTable 中。一切都是可选的。

假设我同时提供标准#1 和#2。在这种情况下,我想以不同的别名分别加入SpecialTable 两次,因为这些条件不相互依赖。

// Optional Criterion #1
if (searchCriteria.getSpecialId() != null) {
    criteriaQuery.createAlias("specialTable", "specialTableJoin1", JoinType.INNER_JOIN);
    criteriaQuery.add(Restrictions.eq("specialTableJoin1.id", searchCriteria.getSpecialId()));
}   

// ...

// Optional Criterion #2
if (!StringUtils.isBlank(searchCriteria.getRequestPublicationTitle())) {

    criteriaQuery.createAlias("specialTable", "specialTableJoin2", JoinType.LEFT_OUTER_JOIN);

    String titleForQuery = "%" + searchCriteria.getRequestPublicationTitle().replaceAll("^.*,", "").trim() + "%";
    Disjunction requestOrPublicationTitle = Restrictions.disjunction();
    requestOrPublicationTitle.add(Restrictions.ilike("title", titleForQuery));
    requestOrPublicationTitle.add(Restrictions.ilike("specialTableJoin2.publicationTitle", titleForQuery));

错误:

org.hibernate.QueryException: duplicate association path: specialTable

有什么解决办法吗?我的别名不同,但它仍然不起作用。

【问题讨论】:

    标签: hibernate hibernate-criteria


    【解决方案1】:

    这是一个旧的 Hibernate 错误 - https://hibernate.atlassian.net/browse/HHH-879 - 自 2005 年以来仍然存在!

    唯一的解决方案是事先定义所有别名,而不是为每个使用的标准定义别名。但是,如果在别名创建中使用了不同的 JoinType(INNER 与 LEFT_OUTER_JOIN),这可能会成为问题。如果都是相同的 JoinType,你就设置好了。

    我采用的解决方法是定义一个通用的 LEFT_OUTER_JOIN,其中需要 INNER/LEFT_OUTER_JOIN。 Left Join 仍然适用于 Criterion #1,因为它受 Value=... 的约束,因此与原始 Inner Join 没有真正的区别。

    // Prepare aliases (joins)
    // -----------------------
    if (searchCriteria.getSpecialId() != null || !StringUtils.isBlank(searchCriteria.getTitle())) {
        // Note: LEFT JOIN for both Special ID and Title,
        // since Hibernate Criteria API only allows 1 alias & join per Table (https://hibernate.atlassian.net/browse/HHH-879), and the 2nd criterion requires a Left Outer Join
        criteriaQuery.createAlias("specialTable", "st", JoinType.LEFT_OUTER_JOIN);                                                  
    }
    // ... All other aliases prepared ...
    
    // Actual Criteria
    // ... use the "st" single alias
    

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多