无法在spring data jpa中连接2个表

py49o6xq  于 2023-01-26  发布在  Spring
关注(0)|答案(2)|浏览(165)

我是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吗?
谢谢

3npbholx

3npbholx1#

assignee的类型为User,而不是Integer,但您发送的assignee:1无法反序列化您的请求。
应该是
assignee:{ userId:1 }
但是在稍后尝试持久化Task期间无论如何它都会失败(但这是另一个问题)

4c8rllxm

4c8rllxm2#

所以基本上你要为一个id为1的User创建一个Task
您所需要做的就是将User对象Map到Task对象。
请尝试以下操作

@Override
public TaskResponse addTask(Task task) {
    User assignee = new User();
    assignee.setUserId(task.assignee);

    task.setAssignee(assignee);

    taskRepository.save(task);
    return mapToTaskResponse(task);
}

相关问题