尝试使用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"
}
如果我通过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实体还是以某种方式可配置?
答案 0 :(得分:1)
从@JsonIgnore
删除task
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"
}
答案 1 :(得分:0)
简单的ManyToOne
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private Task task;
我制作了fetch = FetchType.EAGER(延迟获取仅获取特定表中的值,如果我们还希望使用映射的实体值,那么将使用eager),然后将其删除@JoinColumn(默认情况下,hibernate在其中创建字段“ task_id”评论表),
我对评论的Json对象是
{
"comment": "Some text",
"task": {
"id":1
}
}