开始进入Spring Boot,并使用jpa存储库来持久保存本地mysql数据库,而我的插入遇到麻烦。我将其简化为我的用户和任务类,一个用户可以有一个任务,并且我在任务类中使用@ManyToOne注释进行一个方向映射。在邮递员中调用端点时,出现错误,并且跟踪显示user_id列为空(这是用户映射的列)。
要调试,我在实际taskRepo.save(task)方法的task服务类中设置了一个断点,看来user_id实际上是。我尝试了一对多和多对一的双向映射,但按选项进行映射却无济于事。
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true)
private Long id;
private Long postId;
@Column(unique = true, nullable = false)
private String username;
@Column(unique = true, nullable = false, name = "email")
private String email;
@Column(nullable = false)
private String password;
@Id
@GeneratedValue(strategy =GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "taskName", nullable = false)
private String taskName;
@Column(name = "description")
private String description;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Autowired
private TaskService taskService;
@GetMapping("/getAllTask")
public List<Task> getAllTasks(){
return taskService.getAllTask();
}
@CrossOrigin(origins = "http://localhost:3000")
@PostMapping("/addTask")
public void addTask(@RequestBody Task task){
taskService.addTask(task);
}
@Autowired
private TaskRepo taskRepo;
public List<Task> getAllTask(){
List<Task> tasks = new ArrayList<>();
taskRepo.findAll().forEach(task -> tasks.add(task));
return tasks;
}
public void addTask(Task task){
taskRepo.save(task);
}
{
"taskName": "Task 1",
"description": "This is the first item",
"user_id": 1
}
{
"timestamp": "2019-04-02T02:15:06.989+0000",
"status": 500,
"error": "Internal Server Error",
"message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"path": "/task/addTask"
}
[enter image description here][1] ERROR 30016 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'user_id' cannot be null
答案 0 :(得分:0)
您的json格式不正确。 user_id
不是Task
的字段。
您的json应该看起来像这样:
{
"taskName": "Task 1",
"description": "This is the first item",
"user": {
"id": 1
}
}
user
json字段是指
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
由于User
是一个对象,因此需要将其表示为JsonObject
。