JPA CriteriaQuery Join-如何在子元素上进行联接? [英] JPA CriteriaQuery Join - how to join on a subelement?
问题描述
我正在尝试使用条件查询来执行联接.
I am trying to use criteria queries to perform a join.
我的班级结构是这样的:
My class structure is like this:
@Entity
class Parent {
Intermediate intermediate;
}
@Entity
class Intermediate {
Set<Child> children
}
@Entity
class Child {
String someProperty;
}
我正在尝试让所有父母中至少一个孩子具有匹配的财产,但无法确定如何加入.如果没有中间对象,那将很容易:
I am trying to get all parents where at least one child has a matching property, but cannot work out how to do the joining. If the Intermediate object wasn't there, it would be quite easy:
// 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" );
但是使用中间实体这样做会破坏它
But doing this with the intermediate entity breaks it
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]
te-entitymanager-4.2.0.Final.jar:4.2.0.Final]
在此示例中,我可以为孩子设计Path对象,但是JPA似乎不想让我使用Path对象而不是Root对象进行Join.
I can work out the Path object for the child in this example, but JPA doesn't seem to want to let me make a Join using a Path object instead of a Root one.
有人可以帮我吗?谢谢
推荐答案
我认为您的课程必须是这样的.
I think your classes need to be something like this.
@Entity
class Parent {
@OneToOne
Intermediate intermediate;
}
@Entity
class Intermediate {
@OneToOne(mappedBy="intermediate")
Parent parent;
@OneToOne
Set<Child> children
}
@Entity
class Child {
String someProperty;
}
然后您可以按照以下步骤进行连接.
Then you can do the join as it follows.
CriteriaBuilder builder = ...
CriteriaQuery<Parent> query = ...
Root<Parent> root = query.from( Parent.class );
Join<Parent, Child> join = root.join("intermediate").join("children");
这篇关于JPA CriteriaQuery Join-如何在子元素上进行联接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!