![](/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.