如何发布引用到另一个表的新记录



尝试使用 Spring Data Rest:

我有 2 个实体,具有@ManyToOne关系:

@Data
@Entity
@NoArgsConstructor
@Table(name = "tasks")
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 150)
private String title;
@Lob
private String description;
}
@Data
@Entity
@NoArgsConstructor
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "task_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private Task task;
@Lob
@Column(nullable = false)
private String comment;
}

我无法添加应与 1 个任务关联的新评论

POST http://localhost:9000/api/comments
Content-Type: application/json
{
"comment": "Some text",
"task_id": 1
}

此请求返回:

POST http://localhost:9000/api/comments
HTTP/1.1 409 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 01 Jul 2020 16:36:25 GMT
Keep-Alive: timeout=60
Connection: keep-alive
{
"cause": {
"cause": {
"cause": null,
"message": "Column 'task_id' cannot be null"
},
"message": "could not execute statement"
},
"message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
}
  1. 首先我创建了任务
  2. 尝试向任务添加注释

如果我通过 id 获得任务:

GET http://localhost:9000/api/tasks/1
Accept: application/json

它将返回它:

{
"title": "new task",
"description": "more content",
"priority": "HIGH",
"todoDate": "2020-07-02 10:50",
"_links": {
"self": {
"href": "http://localhost:9000/api/tasks/1"
},
"task": {
"href": "http://localhost:9000/api/tasks/1"
}
}
}

我做错了什么? 我应该使用双向方法并将@OneToMany添加到任务实体还是可以以某种方式配置?

task中删除@JsonIgnore

public class Comment {
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "task_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
// @JsonIgnore
private Task task;
}

并发布此内容:

{
"comment": "Some text",
"task": "http://localhost:9000/api/tasks/1"
}

用于简单的ManyToOne

@ManyToOne(fetch = FetchType.EAGER, optional = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private Task task;

我做了 fetch = FetchType.EAGER(惰性获取只获取特定表中的值,如果我们也想要映射的实体值,那么使用 eager (,并删除@JoinColumn(默认情况下休眠会在注释表中创建一个字段"task_id"(,

我的 Json 评论对象是,

{
"comment": "Some text",
"task": {
"id":1
}
}

最新更新