我已經在這里待了幾個小時,似乎找不到問題所在。
對于一些背景關系,這是我的資料庫架構:

這是我的Student課:
@Entity
@NoArgsConstructor
@Data
public class Student {
@NotNull
@Id
private long number;
@NotBlank
@NotNull
private String name;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "students", cascade = CascadeType.ALL)
@JsonIgnore
private List<Task> tasks;
}
這是我的Task課:
public class Task {
@NotNull
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotBlank
@NotNull
private String description;
@ManyToMany
@JoinTable(
name = "student_tasks",
joinColumns = @JoinColumn(name = "tasks_id"),
inverseJoinColumns = @JoinColumn(name = "student_number")
)
@JsonIgnore
private List<Student> students;
}
因此,我的 H2 資料庫結構如下所示:

我正在嘗試通過休息控制器向學生添加任務(休息控制器作業正常):
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class MyRestController {
@Autowired
private Exercises exercises;
[...]
@PostMapping(value = "/students/student/{studentId}/complete/{taskId}")
public void completeTask(
@PathVariable(value = "studentId") long studentId,
@PathVariable(value = "taskId") long taskId
) {
exercises.completeTask(studentId, taskId);
}
}
這是我的Exercises課:
@Service
@Slf4j
public class Exercises {
@Autowired
private StudentDB studentDB;
@Autowired
private TaskDB taskDB;
[...]
public void completeTask(long studentId, long taskId) {
var student = studentDB.findById(studentId).orElse(null);
var task = taskDB.findById(taskId).orElse(null);
log.info(student.toString());
log.info(task.toString());
log.info(student.getTasks().toString());
student.getTasks().add(task);
studentDB.save(student);
log.info(studentDB.findById(studentId).orElse(null).getTasks().toString());
}
}
以下是代碼中的日志:
2022-01-04 14:29:42.827 INFO : Student{number=3, name='StudentC'}
2022-01-04 14:29:42.828 INFO : Task{id=4, description='Exercice 4'}
2022-01-04 14:18:54.180 INFO : [Task{id=1, description='Exercice 1'}, Task{id=2, description='Exercice 2'}, Task{id=3, description='Exercice 3'}]
2022-01-04 14:18:54.189 INFO : [Task{id=1, description='Exercice 1'}, Task{id=2, description='Exercice 2'}, Task{id=3, description='Exercice 3'}, Task{id=4, description='Exercice 4'}]
如您所見,Task 似乎確實已添加到資料庫中 - 除了它沒有:(

?? 應該有一個“4, 3”(4 是任務 ID,3 是學生“編號”)。
哦,當我在做的時候,這是我的StudentDB課:
public interface StudentDB extends CrudRepository<Student, Long> {}
我對Spring還是很陌生,所以可能只是我錯過了一些東西:/
提前感謝您的幫助!
uj5u.com熱心網友回復:
正如@MauricePerry 評論的那樣,將學生添加到任務而不是將任務添加到學生作業??
對于遇到相同問題的任何人,我現在有以下代碼:
@Service
@Slf4j
public class Exercises {
@Autowired
private StudentDB studentDB;
@Autowired
private TaskDB taskDB;
public void completeTask(long studentId, long taskId) {
var student = studentDB.findById(studentId).orElse(null);
var task = taskDB.findById(taskId).orElse(null);
task.getStudents().add(student);
taskDB.save(task);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/406482.html
標籤:
