【发布时间】:2022-01-04 13:40:35
【问题描述】:
我已经在这几个小时了,似乎找不到问题。
对于一些上下文,这是我的数据库架构:
这是我的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 还是很陌生,所以可能只是我错过了一些东西:/
提前感谢您的帮助!
【问题讨论】:
-
尝试将学生添加到任务中,而不是相反
-
@MauricePerry 成功了!知道为什么吗?是因为
students属性使用了JoinTable吗? ?????? -
@MauricePerry(顺便说一句谢谢!!:))
标签: java spring spring-boot hibernate spring-data-jpa