簡體   English   中英

Spring JPA 基於接口的投影在連接實體上返回 null

[英]Spring JPA Interface based projection returns null on a joined entity

我正在嘗試使用 BookAuthorView 接口獲取書籍 ID 以及作者實體。

public class Book {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @OneToOne(mappedBy = "book", cascade = CascadeType.REMOVE)
  private Author author;

  ...other properties/joined entities...

  ...getters/setters...
}

public class Author {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @OneToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "bookId")
  private Book book;

  ...getters/setters...
}

圖書存儲方法

BookAuthorView getById(final Long id);

 

投影界面

public interface BookAuthorView {
   Long getId();
   Author getAuthor();
}

但是,當我在 rest 端點中收到有效負載時,這會導致作者屬性 null。 我查看了 SQL 日志,它確實投射了作者的所有屬性。 不幸的是,我在響應負載中沒有看到它。 如果我需要包含更多詳細信息,請告訴我。 任何回復/評論表示贊賞。

這是Blaze-Persistence Entity Views的完美用例。

Blaze-Persitence 是 JPA 之上的查詢構建器,它支持 JPA model 之上的許多高級 DBMS 功能。 我在它上面創建了實體視圖,以便在 JPA 模型和自定義接口定義模型之間輕松映射,例如 Spring 數據投影。 這個想法是您以您喜歡的方式定義您的目標結構,並通過 JPQL 表達式將 map 屬性(getter)定義到實體 model。 由於屬性名稱用作默認映射,因此您通常不需要顯式映射,因為 80% 的用例是擁有作為實體 model 子集的 DTO。

您可以將 Blaze-Persistence Entity-Views 想象成 Spring 數據投影中的類固醇。 它更強大,最重要的是,允許您使用 model。

您可以像這樣在BookAuthorView中使用實體Author

@EntityView(Book.class)
public interface BookAuthorView {
   Long getId();
   Author getAuthor();
}

但是將實體混入其中總是會帶來麻煩,因此我建議您改為這樣做

@EntityView(Book.class)
public interface BookAuthorView {
   Long getId();
   AuthorView getAuthor();
}
@EntityView(Author.class)
public interface AuthorView {
   Long getId();
   String getName(); // Other attributes you need
}

查詢是將實體視圖應用於查詢的問題,最簡單的就是通過 id 進行查詢。

BookAuthorView dto = entityViewManager.find(entityManager, BookAuthorView.class, id);

但是 Spring 數據集成允許您幾乎像 Spring 數據投影一樣使用它: https://persistence.blazebit.com/documentation/entity-view/mandata-features_html/index。

它只會獲取您告訴它獲取的映射

暫無
暫無

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

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