我正在使用 Spring Data JPA 开发 Spring Boot 2.3.4 Web 应用程序。
我想将 Hibernate 2 级查询缓存用于带有 @EntityGraph 的存储库方法。但是,如果数据已经在二级缓存中,除非我打开了 Spring 的 Open Session In View,否则在生成 Thymeleaf 视图时会出现 LazyInitializationException。第一次从数据库或没有二级缓存的情况下获取数据时,即使 spring.jpa.open-in-view=false 也一切正常。此外,如果我启用 spring.jpa.open-in-view 从缓存中获取数据而不选择数据库时也不例外。
使用 Hibernate 二级缓存时,如何让 Hibernate 一次获取 @EntityGraph 中指定的所有关联?
这是我的存储库方法:
@org.springframework.data.jpa.repository.QueryHints({@javax.persistence.QueryHint(name = "org.hibernate.cacheable", value = "true")})
@EntityGraph(attributePaths = { "venue.city", "lineup.artist", "ticketLinks" }, type = EntityGraphType.FETCH)
Optional<Event> findEventPageViewGraphById(long id);
和实体的一部分:
@Entity
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "venue_id")
private Venue venue;
@OneToMany(mappedBy = "event", cascade = CascadeType.ALL, orphanRemoval = true)
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@OrderBy("orderId")
private Set<TicketLink> ticketLinks = new LinkedHashSet<>();
@OneToMany(mappedBy = "event", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("orderId")
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<ArtistEvent> lineup = new LinkedHashSet<>();
}