Spring Boot — JPA Entity Relationships

Asep Saputra
Code Storm
Published in
3 min readMay 10, 2021

--

In this post, I’ll implement how to work with relationships between entities in Spring Data REST with JPA.

Spring Boot — JPA Entity Relationships
Photo by Campaign Creators on Unsplash

Generally, the entity classes are treated as relational tables, therefore the relationships between Entity classes are as follows:

@OneToOne Relationship

One to One relationship is a condition where data in a table only has a relationship to one data in another table. For example,

The diagram explains One-To-One relationship as follows:

a simple word to express this is:

One employee only has one account and vice versa.

  • Employee
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

private String name;
private String email;

// constructors, getters, setters
}
  • Account
@Entity
@Table(name = "account")
public class Account {

@Id
private int id;

private String password;

@OneToOne
@JoinColumn(name = "id", referencedColumnName = "id")
private Employee employee;
// constructors, getters, setters
}

@OneToMany and @ManyToOne…

--

--