我正在使用Spring Boot实现GraphQL服务器,但是,在为具有多对多关系的模型编写解析器时遇到了一些麻烦。下面的resolver类中的函数getBooks
引发以下错误:
package com.example.DemoGraphQL.resolver;
import java.util.Set;
import java.util.stream.Collectors;
import com.coxautodev.graphql.tools.GraphQLResolver;
import com.example.DemoGraphQL.model.Author;
import com.example.DemoGraphQL.model.Book;
import com.example.DemoGraphQL.repository.AuthorRepository;
import com.example.DemoGraphQL.repository.BookRepository;
public class AuthorResolver implements GraphQLResolver<Book> {
private BookRepository bookRepository;
public AuthorResolver(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
public Iterable<Book> getBooks(Author author) {
Set<Long> ids = author.getBooks().stream().map(book -> book.getId()).collect(Collectors.toSet());
return bookRepository.findAll(ids);
}
}
错误消息:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.DemoGraphQL.model.Author.books, could not initialize proxy - no Session
当我仅查询给定模型的一个对象时,便能够实现类似的解析器。任何建议表示赞赏。
答案 0 :(得分:0)
我通过将fetch=FetchType.Eager
添加到我的多对多装饰器中来解决此问题。
@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
这显然不是大规模的解决方案。