【发布时间】:2019-04-02 02:54:01
【问题描述】:
开始进入 Spring Boot 并使用 jpa 存储库来持久化本地 mysql 数据库,但插入时遇到问题。我将它简化为我的用户和任务类,用户可以有一个任务,我在任务类中使用@ManyToOne 注释进行一个方向映射。当在 post man 中调用端点时,我收到一个错误,并且跟踪表明 user_id 列为空(这是来自用户的映射列)。
为了调试,我在实际 taskRepo.save(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
【问题讨论】:
标签: java mysql hibernate jpa spring-data-jpa