【发布时间】:2020-08-01 14:22:33
【问题描述】:
我正在构建一个简单的 Spring Boot 博客应用程序。这个应用程序有两个实体用户和帖子。 user表保存用户数据,主键为id,post表保存内容信息,用户信息为外键“postedBy”,指的是用户表的id。一个用户可以有很多帖子。
基于此,我设计了如下所示的实体类。
@Entity
@Table
public class User {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
private String name;
private String email;
}
@Entity
@Table
public class Post {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
private String title;
@ManyToOne
@JoinColumn(name = "id" , insertable = false,updatable = false)
private User postedBy;
private String content;
}
作为一个用户可以有多个帖子,我有用户 @ManyToOne 注释,它通过 @JoinColumn
映射到用户的 id我正在使用 JpaRepository 接口,然后通过休息控制器公开。
但是当我发送正文插入如下帖子时
{
"title":"The Graphql way of design",
"postedBy":"402880ee73aa45570173aa462ea00001",
"content":" The content of blog "
}
它抛出以下错误
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.graphql.blog.model.User` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('402880ee73aa45570173aa462ea00001'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.graphql.blog.model.User` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('402880ee73aa45570173aa462ea00001')
at [Source: (PushbackInputStream); line: 3, column: 13] (through reference chain: com.graphql.blog.model.Post["postedBy"])]
我期待postedBy 列将存储“402880ee73aa45570173aa462ea00001”,因为用户已经存在,作为响应,它会发送用户详细信息,自动获取该帖子的用户详细信息。
【问题讨论】:
-
我认为您也可以尝试在对象中添加一个新属性
postedById,使用与postedBy相同的注释,但用insertable = true, updatable = true标记这个。这样,您可以尝试将 json 中的海报 id 发送为postedById。
标签: java spring spring-boot spring-data-jpa