我是spring-data-jpa的新手。我正在开发一个任务管理系统。我有2个实体:
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long taskId;
private String title;
private String description;
private Status status;
@OneToOne
@JoinColumn(name = "user_id", referencedColumnName = "userId")
private User assignee;
以及:
@Entity
@Table(name = "tbl_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
private String name;
private String email;
private Active active;
private String password;
}
我有一个创建新任务的端点:
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public TaskResponse addTask(@Valid @RequestBody Task task){
return taskService.addTask(task);
}
这是实现:
@Override
public TaskResponse addTask(Task task) {
taskRepository.save(task);
return mapToTaskResponse(task);
}
发送请求时收到的错误是:
2023-01-24 15:10:01.825 WARN 1961 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.tasksmanagement.entity.User` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.tasksmanagement.entity.User` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 5, column: 17] (through reference chain: com.tasksmanagement.entity.Task["assignee"])]
我不知道我做错了什么。基本上我创建了一个用户,并在请求中发送了该用户的ID(有效负载中的受让人字段-随附屏幕截图),以便将新任务分配给该用户。有人能帮助我理解请求的问题吗?我应该发送其他东西来代替用户ID吗?
谢谢
2条答案
按热度按时间3npbholx1#
assignee
的类型为User
,而不是Integer
,但您发送的assignee:1
无法反序列化您的请求。应该是
assignee:{ userId:1 }
但是在稍后尝试持久化
Task
期间无论如何它都会失败(但这是另一个问题)4c8rllxm2#
所以基本上你要为一个
id
为1的User
创建一个Task
。您所需要做的就是将
User
对象Map到Task
对象。请尝试以下操作