所以我已经被这个问题困扰了大约半天,所以我想知道我是否只是把事情变得过于复杂了。
我的应用程序具有三个不同的 Java 对象类:Grandparent、Parent 和 Child。每个祖 parent 都包含一个 parent 列表,每个 parent 都包含一个 child 列表。 Child 有一个“isWellBehaved”属性,它是一个 boolean 值。
我们使用 Spring Data JPA 和 Hibernate 将数据映射到数据库。我们的应用程序包含大量嵌套实体和循环关系,我们依靠投影来缩小请求大小。
问题:给定祖 parent ID,我想返回所有 parent 的列表(作为投影)。我希望每个 parent 都包含一个 child 预测列表,但前提是 child 表现良好。集合中的其余子项应从集合中过滤掉。
实现这一目标的最简单方法是什么?我们目前没有使用 Hibernate 过滤器,而且我也不热衷于介绍它们,因为我们在其他地方不太可能需要它们(无论哪种方式,它是否适合此目的?)。我使用过JPA Criteria API 谓词(很少),但发现很难使其适应这种特定场景。 native 查询是正确的选择吗?我已经开始朝着这个方向前进,但由于所有嵌套的依赖关系,在将所有字段映射到我们的 Spring 实体时遇到了一些问题,所以只是想确保在继续之前我什至朝着正确的方向前进。
我的(简化的)父实体类如下所示:
@Entity
@Table(name="parent"
public class Parent {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="parent_id")
Integer id;
Integer grandparentId;
@OneToMany(mappedBy = "parent")
List<Child> children;
}
子类:
@Entity
@Table(name="child"
public class Child {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="child_id")
Integer id;
@ManyToOne
@JoinColumn(name="parent_id")
Parent parent;
boolean isWellBehaved;
}
父存储库接口(interface):
@RepositoryRestResource(excerptProjection = ParentProjection.class)
public interface ParentRepository extends JpaProjectionRepository<Parent, Integer, ParentProjection> {
List<ParentProjection> findAllByGrandparent_Id(Integer grandpaId);
}
最佳答案
您可以在集合上使用hibernate的@Where注释。会是这样的
@Entity
@Table(name="parent"
public class Parent {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="parent_id")
Integer id;
Integer grandparentId;
@Where(clause = "isWellBehaved=true")
@OneToMany(mappedBy = "parent")
List<Children> children;
}
关于java - 在 Spring Data JPA 中获取父实体列表以及经过过滤的子实体集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56798402/