當應用程序基於Spring Boot時,不會考慮定義的實體圖。相反,在JUnit測試期間一切正常。彈簧數據JPA實體圖不適用於Spring Boot
域很簡單:書籍及其類別(多對多關係)。
Book類:
@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;
Category類:
@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());
}
任何建議,如何讓實體的圖形時,應用程序在春季啓動運行工作?
那麼,什麼是問題?這裏是NamedEntityGraph的文檔,https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs002.htm –
問題是如何獲取實體圖工作,以及爲什麼在Spring上應用引導忽視它們。 –
我想,這可能是有幫助的:http://stackoverflow.com/questions/26291143/spring-data-jpa-jpaspecificationexecutor-entitygraph –