![](/img/trans.png)
[英]Spring Data JPA + Hibernate save children entities without finding parent firstly
[英]Fetching a list of parent entities with a filtered collection of children in Spring Data JPA
所以我在这个问题上停留了大约半天,所以我想知道我是否只是使事情变得过于复杂。
我的应用程序具有三种不同的Java对象类:祖父母,父母和孩子。 每个祖父母都包含父母名单,每个父母都包含孩子名单。 子级具有“ isWellBehaved”属性,该属性是布尔值。
我们正在使用Spring Data JPA和Hibernate来将数据映射到数据库。 我们的应用程序包含许多嵌套实体和循环关系,并且我们依靠投影来减小请求大小。
问题:给定祖父母编号,我想返回所有父母的列表(作为投影)。 我希望每个父项都包含一个子项投影列表,但前提是该子项行为良好。 集合中的其余孩子应从集合中过滤掉。
实现这一目标的最简单方法是什么? 目前我们不使用Hibernate过滤器 ,我也不愿意引入它们,因为我们不太可能在其他任何地方使用它们(无论哪种方式,都适合于此目的吗?)。 我使用了JPA Criteria API谓词 (很少),但发现很难使其适应这种特殊情况。 是本机查询吗? 我已经开始朝着这个方向前进,但是由于所有嵌套的依赖关系,在将所有字段映射到我们的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;
}
父存储库接口:
@RepositoryRestResource(excerptProjection = ParentProjection.class)
public interface ParentRepository extends JpaProjectionRepository<Parent, Integer, ParentProjection> {
List<ParentProjection> findAllByGrandparent_Id(Integer grandpaId);
}
如您所说:
我希望每个父项都包含一个子项投影列表,但前提是该子项行为良好。
List<childerns>allChilderns=parentsList.stream().map(parent>dao.findchildernByParentId()).collect(Collectors.List());
allChilderns.stream().filter(childern->childern.isWellBehaved()==true).collect(Collectors.toList());
让我知道:)
您可以在集合上使用休眠的@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.