英文:
Hibernate predicate to get children based on parent
问题
我有以下的结构:
@Entity
class Parent {
@Id
int id;
@OneToMany(fetch = FetchType.LAZY)
List<Child> children;
}
@Entity
public class Child {
@Id
int id;
@ManyToOne
Parent parent;
}
我想根据特定的父母 ID 获取子元素。因为我想对结果进行分页,所以我想为子元素构建谓词,而不仅仅获取父元素并以这种方式获取所有子元素。
所以,我想为 Child 查询构建类似以下的谓词:
builder.equal(root.get("parent.id"), parentId);
但这显然不起作用。那么,正确的方法是什么?
谢谢!
英文:
I have following structure:
@Entity
class Parent {
@Id
int id;
@OneToMany(fetch = FetchType.LAZY)
List<Child> children;
}
@Entity
public class Child {
@Id
int id;
@ManyToOne
Parent parent;
}
I want to get children based on a specific parent id. As I want to paginate the result I want to build predicate for children and not just fetch parent and get all the children this way.
So, I imagining predicate like this for the Child query:
builder.equal(root.get("parent.id"), parentId);
But this obviously will not work. So, what is the right way to do it?
Thanks
答案1
得分: 1
parent.id
不是属性名称,而是属性路径。如果你阅读Java文档,你会发现Path#get
需要一个属性名称。所以要修复这个问题,使用root.get("parent").get("id")
。
英文:
parent.id
is not a property name, but a property path. If you read the java doc, you will see that Path#get
requires a property name though. So to fix this, use root.get("parent").get("id")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论