簡體   English   中英

延遲加載在 Spring 數據 jpa 中不起作用

[英]lazy load does not work in Spring data jpa

我正在使用 spring jpa 和 lombok 來定義 java bean 主題。 每個主題都會有很多評論。 我的onetomany配置是

@Entity
@Table(name = "TOPIC")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Topic implements Serializable {

@OneToMany(
            fetch = FetchType.LAZY, 
            cascade = CascadeType.REMOVE,
            mappedBy = "topic"
        )
    private Set<Comment> comments= new HashSet<>();

我創建的寧靜的api是這樣的。 序列化似乎是問題所在,它總是獲取評論。 正如克里斯所提到的,我已經添加了@JsonIgnore ,它似乎解決了這個問題。 但是如果我想加載評論, @JsonIgnore不會在序列化中返回評論。

@GetMapping("/topics")
   public List<Topic> getAllTopics(@SortDefault(sort = "topicName", direction = DESC) Sort sort) {
      return topicService.getAllTopics(sort);
   }

我假設您在使用findAll()時調試了 SQL 並且還看到作為 SQL 查詢獲取的評論?

文檔中:

LAZY 策略是對持久性提供程序運行時的提示

這里的提示意味着不能保證持久性提供者服從 LAZY fetching。 這只是一個建議,考慮對此使用 LAZY 加載可能是明智的。

因此,您的持久性提供者可能只看到 5 條評論並決定加載這些評論。

如果您尚未檢查 SQL 或想嘗試其他方法來檢查加載 LAZY 的 state,如果有助於調試發生的情況,您可以看到這個問題

我相信你真正需要的是一個投影 延遲獲取不是可以輕松配置運行時的東西,更不用說防止加載延遲項。

相反,您應該使用DTO class 聲明要從數據庫中獲取的數據,或者使用告訴顯示內容的界面更好。

請參閱下面的存儲庫(我省略了服務部分,因為您也沒有顯示它):

public interface TopicRepository extends PagingAndSortingRepository<Topic, Long> {  
    List<Topic> findAll(Sort sort);

    // bean convention getter declarations for fields to fetch
    interface TopicWithoutComments {
        Long getId();
        String getTopicName();
    }

    List<TopicWithoutComments> findAllBy(Sort sort);
}

現在 yiu 需要單獨的方法(或您想要決定是否顯示評論的任何其他方式),首先是原始方法:

@GetMapping("/topics")
public List<Topic> getAllTopics(@SortDefault(sort = "topicName", 
        direction = Direction.DESC) Sort sort) {
    return topicRepository.findAll(sort);
}

它輸出如下內容:

Hibernate: select comments0_.topic_id as topic_id3_0_0_, comments0_.id as id1_0_0_, comments0_.id as id1_0_1_, comments0_.text as text2_0_1_, comments0_.topic_id as topic_id3_0_1_ from comment comments0_ where comments0_.topic_id=?
...

對於找到的每個主題。 那么投影端點可能是這樣的:

@GetMapping("/topics/wocomments")
public List<TopicWithoutComments> getAllTopicsWithoutComments(
        @SortDefault(sort = "topicName",
            direction = Direction.DESC) Sort sort) {
    return topicRepository.findAllBy(sort);
}

這將只打印一行(假設在 Topic 上沒有其他一對多關系):

Hibernate: select topic0_.id as col_0_0_, topic0_.topic_name as col_1_0_ from topic topic0_ order by topic0_.topic_name desc

暫無
暫無

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

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