【问题标题】:Spring Boot CrudRepository not saving entities to my databaseSpring Boot CrudRepository 没有将实体保存到我的数据库中
【发布时间】: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


【解决方案1】:

正如@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);
    }
}

【讨论】:

  • 是的:当您将@JoinTable 放在Task 中时,它成为拥有方,而Student 是反方。
  • 哦!我会保存任务而不是学生
  • @MauricePerry oop 是的,那是我的错,我在从我的原始帖子复制/粘贴时忘记更改那部分代码(⩾﹏⩽)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 2018-05-27
  • 2022-01-07
  • 2018-05-12
相关资源
最近更新 更多