Hibernate谓词以基于父项获取子项。

huangapple go评论49阅读模式
英文:

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&lt;Child&gt; 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(&quot;parent.id&quot;), 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(&quot;parent&quot;).get(&quot;id&quot;)

huangapple
  • 本文由 发表于 2023年2月13日 22:54:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75437521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定