![](/img/trans.png)
[英]Using Spring data JPA EntityGraph with LAZY load mode for NamedAttributeNode field
[英]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);
}
我相信你真正需要的是一個投影。 延遲獲取不是可以輕松配置運行時的東西,更不用說防止加載延遲項。
相反,您應該使用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.