Skip to content

Spring Boot CrudRepository not saving entities to my database

I’ve been at this for a few hours now and can’t seem to find the issue.

For a bit of context, here is my database schema :

Database schema

Here is my Student class :

@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;
}

And here is my Task class :

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;
}

My H2 Database structure therefore looks like this :

H2 Database structure

I am trying to add a task to a student through a rest controller (the rest controller works fine) :

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

Here is my Exercises class :

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

Here are the logs from the code :

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'}]

As you can see, the Task does seem to be added to the database – except it doesn’t 🙁

Database data

☝️ There should be a “4, 3” (4 being the task id and 3 the student “number”).

Oh, and while I’m at it, here is my StudentDB class :

public interface StudentDB extends CrudRepository<Student, Long> {}

I’m still quite new to Spring so it’s probably just me missing something :/
Thanks in advance for your help !

Answer

As @MauricePerry commented, adding the student to the task instead of adding the task to the student worked 🧐

For anyone encountering the same issue, I now have the following code :

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