【问题标题】:Hibernate field multiple aliasHibernate 字段多个别名
【发布时间】:2012-03-04 19:53:36
【问题描述】:

我有一个实体,它有集合字段(参数)。可以有很多参数。我想为每个独特的参数进行独特的连接。即p1.id = ? AND p2.id = ? AND p3.id = ?等。

在 Hibernate 中,当我尝试为同一字段创建别名时,它会抛出异常并显示有关重复别名的消息。

如何实现字段的多个连接?

我正在使用 spring 框架、hibernate 和 postgresql。

提前致谢。

【问题讨论】:

  • 向我们展示查询代码,以及异常的堆栈跟踪。
  • 解决了这个问题。在这个链接底部的“forum.hibernate.org/viewtopic.php?f=1&t=943274”说:“OuterJoinLoader 有一个严重的限制,它阻止了同一个关联被加入两次。”这对我来说很重要。所以我决定用 HQL 而不是 Criteria API 来解决这个问题。
  • 如果您至少在问题中提到您正在使用 Criteria API,或者您已经展示了您的代码,我可以立即告诉您。

标签: java hibernate spring postgresql


【解决方案1】:

我假设您正在使用 Criteria API。

如果你查看 Hibernate 的源代码,你可以在这里找到问题:

CriteriaQueryTranslator#createAssociationPathCriteriaMap()

private void createAssociationPathCriteriaMap() {
        Iterator iter = rootCriteria.iterateSubcriteria();
        while ( iter.hasNext() ) {
            CriteriaImpl.Subcriteria crit = ( CriteriaImpl.Subcriteria ) iter.next();
            String wholeAssociationPath = getWholeAssociationPath( crit );
            Object old = associationPathCriteriaMap.put( wholeAssociationPath, crit );
            if ( old != null ) {
                throw new QueryException( "duplicate association path: " + wholeAssociationPath );
            }
            int joinType = crit.getJoinType();
            old = associationPathJoinTypesMap.put( wholeAssociationPath, new Integer( joinType ) );
            if ( old != null ) {
                // TODO : not so sure this is needed...
                throw new QueryException( "duplicate association path: " + wholeAssociationPath );
            }
        }
    }

我使用的是 Hibernate 3.3.2。

内部发生的情况是,当您将Criterias 添加到您的根Criteria 时,Hibernate 会创建SubCriterias,然后用您尝试使用的所有路径填充Map(检查下面的代码)如果发现重复,则会抛出异常。

例如,如果您尝试加入:entity0.entity1,然后您再次尝试加入,您将获得Exception。即使使用别名也无法使用,因为 Hibernate 在这里不关心它们。

如果您不加入两次,或者您可以使用 HQL/JPQL,您可以解决此问题。您可以查看更新版本的 Hibernate,但我不确定他们是否修复了这个准错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 2015-04-14
    相关资源
    最近更新 更多