【问题标题】:Spring Data JPA entity graphs are not working with Spring BootSpring Data JPA 实体图不适用于 Spring Boot
【发布时间】:2016-12-03 01:16:31
【问题描述】:

当应用基于 Spring Boot 时,不考虑定义的实体图。相反,在 JUnit 测试期间一切正常。

领域非常简单:书籍及其类别(多对多关系)。
书籍类:

@Entity
@NamedEntityGraph(name = "Book.summary",
attributeNodes = { @NamedAttributeNode("book_id"), @NamedAttributeNode("title")})

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

private String title;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "BOOK_CATEGORY",
        joinColumns = @JoinColumn(name = "book_id", referencedColumnName = "book_id"),
        inverseJoinColumns = @JoinColumn(name = "category_id", referencedColumnName = "category_id"))
private List<Category> categories;

类别类:

@Entity
public class Category {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long category_id;

private String name;

@ManyToMany(mappedBy = "categories")
private List<Book> books;

具有使用已创建实体图的方法的 JPA 存储库:

@Component
@Repository
public interface BookJpaRepository extends JpaRepository<Book, Long> {
@Override
@EntityGraph(value = "Book.summary", type = EntityGraph.EntityGraphType.FETCH)
List<Book> findAll(); }

在 REST 控制器中的使用:

@RequestMapping("/books")
@ResponseBody
public List<Book> getBooksSummary() {
    return bookJpaRepository.findAll();
}

在启动 Spring Boot (mvn spring-boot:run) 并导航到 http://localhost:8080/books 之后,会显示书籍,但会显示它们各自的类别(并且由于无限递归而引发异常:书籍 -> 类别 -> 书籍 -> 类别-> ...)。

测试中的相同代码(使用 SpringJUnit4ClassRunner 运行)按预期工作并且实体图被正确识别。例如,下面的代码没有显示类别,因为正如预期的那样有延迟初始化:

@Test
public void testEntityGraph() {
    List<Book> all = bookJpaRepository.findAll();

    System.out.println(all.get(0).getCategories());
}

有什么建议可以在应用程序在 Spring Boot 上运行时让实体图正常工作吗?

【问题讨论】:

  • 那么,有什么问题?这里是 NamedEntityGraph 的文档,docs.oracle.com/javaee/7/tutorial/…
  • 问题是如何让实体图工作以及为什么 Spring Boot 上的应用程序忽略它们。
  • 我想,这可能会有所帮助:stackoverflow.com/questions/26291143/…
  • 任何对带有LAZY fetchType 的集合的getter 的调用都会导致它被加载。我相信当您在控制器上调用findAll 方法时,它会获取整个实体,包括标记为LAZY 的那些属性。这是导致categories 被加载的序列化。

标签: java spring spring-boot spring-data-jpa entitygraph


【解决方案1】:

正如 Rae Burawes(谢谢!)在 cmets 中指出的那样,这种行为的原因是序列化。
要处理 Jackson 序列化程序获取数据,我们可以使用这些注释:
- com.fasterxml.jackson.annotation.JsonIdentityInfo - 在班级/领域
- com.fasterxml.jackson.annotation.JsonManagedReferencecom.fasterxml.jackson.annotation.JsonIgnore - 现场

更多信息可以在this tutorial找到。

【讨论】:

  • 您可以发布带有这些注释的解决方案吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2020-07-04
  • 2019-09-30
  • 2020-12-08
  • 2021-05-21
  • 2017-05-09
  • 2021-03-01
相关资源
最近更新 更多