【发布时间】:2020-11-26 08:59:38
【问题描述】:
使用 java 构建微服务 -
spring-boot 版本 2.2.6.RELEASE graphql-spring-boot-starter 版本 5.0.2
尝试使用 graphql 突变在 MongoDB 中持久化记录,我通过如下所示的单个对象成功持久化 -
type ParentElement {
id: ID!
type: String
child: String
}
但是在尝试使用嵌套对象时,我看到以下错误 -
原因:com.coxautodev.graphql.tools.SchemaError:预期类型“ChildElement”是 GraphQLInputType,但它不是!一个类型是否只允许用于错误地用作输入类型的对象类型,反之亦然?
我的架构如下-
schema {
query: Query
mutation: Mutation
}
type ChildElement {
make: String
model: String
}
type ParentElement {
id: ID!
type: String
child: ChildElement
}
type Query {
findAllElements: [ParentElement]
}
type Mutation {
createElement(id: String, type: String, child: ChildElement): ParentElement
}
Pojo Classes & Mutation 如下 -
@Document(collection="custom_element")
public class ParentElement {
private String id;
private String type;
private ChildElement child;
}
public class ChildElement {
private String make;
private String model;
}
@Component
public class ElementMutation implements GraphQLMutationResolver {
private ElementRepository elementRepository;
public ElementMutation(ElementRepository elementRepository) {
this.elementRepository = elementRepository;
}
public ParentElement createElement(String id, String type, ChildElement child) {
ParentElement element = new ParentElement()
elementRepository.save(element);
return element;
}
}
@Component
public class ElementQuery implements GraphQLQueryResolver {
private ElementRepository elementRepository;
@Autowired
public ElementQuery(ElementRepository elementRepository) {
this.elementRepository = elementRepository;
}
public Iterable<ParentElement> findAllElements() {
return elementRepository.findAll();
}
}
@Repository
public interface ElementRepository extends MongoRepository<ParentElement, String>{
}
我想在 mongo db 中保存以下 json 表示 -
{
"id": "custom_id",
"type": "custom_type",
"child": {
"make": "custom_make",
"model": "Toyota V6",
}
}
我尝试了几件事,但是在启动服务器时总是遇到同样的异常。上面的json是一个简单的表示。我想保存更复杂的一个,与其他在线示例的不同之处在于,我不想为子元素创建单独的 mongo 对象,如在线提供的 Book-Author 示例所示。
【问题讨论】:
标签: java mongodb spring-boot graphql-java