javaspringspring-dataspring-data-jdbc

Spring Data JDBC Save data as root entity


I have root entity called school. it has many attributes and course is one of them. I have both school repository and course repository to save data independently Course it self has 1-M relationship ( 1 course can have many subjects etc). In terms of the best practice / performance, should I find the school first, then add the course and save or I should save the course independently using the course repo?

  1. I am getting the school like this. School school = schoolRepository.findById(schoolId);
  2. then add course school.addCourse(course);
  3. then save school.

I could simply use courseRepo and save like this as well. courseRepository.save(course)

I want to understand which approach is best/performant.


Solution

  • Spring Data JDBC is strongly based on Domain Driven Design. This means that you should decide from a semantic point of view what parts belong to a single aggregates. Aggregates will be represented by their aggregate root and persist (and load) everything they reference directly or indirectly in one go.

    Other aggregates get referenced only by id, have their own repository which is used to load and save them.

    There is more information about this in https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates

    From what you describe I would assume that School, Course and Subject all are separate Aggregates with their own repository each. Although Subject might actually be part of Course if it doesn't get referenced outside of Course but that would actually surprise me.