JPA CriteriaQuery Join - 如何加入子元素?

时间:2014-04-04 16:10:53

标签: java hibernate jpa

我正在尝试使用条件查询来执行连接。

我的班级结构是这样的:

@Entity
class Parent {
  Intermediate intermediate;
}

@Entity
class Intermediate {
  Set<Child> children
}

@Entity
class Child {
  String someProperty;
}

我试图让所有父母至少有一个孩子有匹配的财产,但无法知道如何加入。如果没有Intermediate对象,那将很容易:

// Here, Intermediate doesn't exist - Parent has the Set<Child> property

CriteriaBuilder builder = ...
CriteriaQuery<Parent> query = ...
Root<Parent> root = query.from( Parent.class );
Join<Parent, Child> join = root.join( "child" );

Path path = join.get( "someProperty" );
Predicate predicate = builder.equal( path, "somevalue" );

但是对中间实体这样做会打破它

CriteriaBuilder builder = ...
CriteriaQuery<Parent> query = ...
Root<Parent> root = query.from( Parent.class );
Join<Parent, Child> join = root.join( "intermediate.child" ); <-- Fails

Caused by: java.lang.IllegalArgumentException: Unable to resolve attribute [intermediate.child] against path
    at org.hibernate.ejb.criteria.path.AbstractPathImpl.unknownAttribute(AbstractPathImpl.java:120) ~[hibernate-entitymanager-4.2.0.Final.jar:4.2.0.Final]
    at org.hibernate.ejb.criteria.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:229) ~[hibernate-entitymanager-4.2.0.Final.jar:4.2.0.Final]
    at org.hibernate.ejb.criteria.path.AbstractFromImpl.join(AbstractFromImpl.java:411) ~[hiberna

TE-的EntityManager-4.2.0.Final.jar:4.2.0.Final]

在这个例子中,我可以计算出子对象的Path对象,但是JPA似乎不想让我使用Path对象而不是Root对象进行连接。

有人能帮帮我吗?感谢

1 个答案:

答案 0 :(得分:1)

我认为你的课程必须是这样的。

@Entity
class Parent {
  @OneToOne
  Intermediate intermediate;
}

@Entity
class Intermediate {
  @OneToOne(mappedBy="intermediate")
  Parent parent;
  @OneToOne
  Set<Child> children
}

@Entity
class Child {
  String someProperty;
}

然后你可以按照以下方式进行连接。

CriteriaBuilder builder = ...
CriteriaQuery<Parent> query = ...
Root<Parent> root = query.from( Parent.class );
Join<Parent, Child> join = root.join("intermediate").join("children");