[英]How to get parent entity with all child entities and child entities of children in Spring/JPA/Hibernate with Lombok
I have these entities where Shop entity is parent:我有这些实体,其中 Shop 实体是父实体:
@Data
@NoArgsConstructor
@Entity
@DynamicUpdate
@Table(name = "Shop", schema = "public")
public class ShopDao {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
private String name;
private String processedStatus;
@OneToMany(mappedBy = "shopDao", cascade = CascadeType.ALL, orphanRemoval = true)
private List<BookDao> bookDaoList;
}
@Data
@NoArgsConstructor
@Entity
@ToString(exclude = {"shopDao"})
@Table(name = "Book", schema = "public")
public class BookDao {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
private String name;
private String author;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "other_id", referencedColumnName = "id")
private OtherDao otherDao;
@ManyToOne
@JoinColumn(name = "shop_id", nullable = false)
private ShopDao shopDao;
}
@Data
@NoArgsConstructor
@Entity
@ToString(exclude = {"bookDao"})
@Table(name = "Other", schema = "public")
public class OtherDao {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
private String metadata;
@OneToOne(mappedBy = "otherDao", fetch = FetchType.EAGER)
private BookDao bookDao;
}
And these are repos:这些是回购:
@Repository
public interface ShopRepo extends JpaRepository<ShopDao, Long> {
@EntityGraph(attributePaths = {"bookDaoList"})
List<ShopDao> findAllByProcessedStatus(String processedStatus);
}
@Repository
public interface BookRepo extends JpaRepository<BookDao, Long> {
}
@Repository
public interface OtherRepo extends JpaRepository<OtherDao, Long> {
}
When i'm using findAllByProcessedStatus()
function, i get BookList inside Shop object correctly, but each Book can't reach their Other objects and i get LazyInitializationException: screenshot当我使用
findAllByProcessedStatus()
函数时,我在 Shop 对象中正确获取了 BookList,但每本书都无法访问它们的其他对象,并且我得到 LazyInitializationException: screenshot
How do i fix that problem?我该如何解决这个问题?
Actually, with spring data's @EntityGraph all you need is :实际上,使用 spring 数据的 @EntityGraph 您只需要:
@Repository
public interface ShopRepo extends JpaRepository<ShopDao, Long> {
@EntityGraph(attributePaths = {"bookDaoList.otherDao"})
List<ShopDao> findAllByProcessedStatus(String processedStatus);
}
This is the most convenient way.这是最方便的方式。 For more complex relations, you could define a @NamedEntityGraph, and provide subgraphs, like so .
对于更复杂的关系,您可以定义一个@NamedEntityGraph,并提供子图,就像这样。
What I find intriguing, is that the BookDao is the owner of this relation, so I would expect it to be eagerly loaded, since you haven't specified a the Lazy fetch mode explicitly ...我觉得有趣的是 BookDao 是这种关系的所有者,所以我希望它能够被急切地加载,因为您没有明确指定 Lazy fetch 模式......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.