Member-only story
Spring JPA relationships
In this article, we’ll take a look at how to work with relationships in spring data JPA.
Let’s assume we have a database that comprises of 4 tables: teachers, courses, modules and departments. We know that these tables will reference each other using foreign keys.
With appropriate relationships set on entities, we can read all data related to an entity without having to write custom queries. For example, when we read a record of a teacher, we’ll also be able to access a record of the department they belong to, their courses etc.
Creating models
These are the models we’ll work with:




Adding relationships
Now let’s add relationships in the database tables.

We can now link entities bases on these columns we just added. Let’s start with a teachers and departments.
A teacher belongs to a department and a department can have one or more teachers, so a one to many…