簡體   English   中英

如何使用 Lombok 在 Spring/JPA/Hibernate 中獲取帶有所有子實體和子實體的父實體

[英]How to get parent entity with all child entities and child entities of children in Spring/JPA/Hibernate with Lombok

我有這些實體,其中 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;
}

這些是回購:

@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> {
}

當我使用findAllByProcessedStatus()函數時,我在 Shop 對象中正確獲取了 BookList,但每本書都無法訪問它們的其他對象,並且我得到 LazyInitializationException: screenshot

我該如何解決這個問題?

實際上,使用 spring 數據的 @EntityGraph 您只需要:

@Repository
public interface ShopRepo extends JpaRepository<ShopDao, Long> {
    @EntityGraph(attributePaths = {"bookDaoList.otherDao"})
    List<ShopDao> findAllByProcessedStatus(String processedStatus);
}

這是最方便的方式。 對於更復雜的關系,您可以定義一個@NamedEntityGraph,並提供子圖,就像這樣

我覺得有趣的是 BookDao 是這種關系的所有者,所以我希望它能夠被急切地加載,因為您沒有明確指定 Lazy fetch 模式......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM