I will make a Spring Boot project school management system. There are many types of users. These users can log in. Do I need to create a user entity and then extend other entities from the user class?
What makes me think here is that there is a relationship between entities.
Teacher, Student, Manager, Guardian
Since I am working on a single entity when creating the login system, I do not know how to do this through different entities.
@Data
@AllArgsConstructor
@RequiredArgsConstructor
@Builder
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
private String username;
private String password;
private String name;
private String surname;
private String gender;
private Role role;
}
@Entity
@Table(name = "teachers")
public class Teacher extends User{
private String subject;
}
@Entity
@Table(name = "students")
public class Student extends User{
private String illness;
@ManyToOne
@JoinColumn(name = "guardian_id")
private Guardian guardian;
}
@Entity
@Table(name = "guardians")
public class Guardian extends User{
@OneToMany(mappedBy = "guardian", cascade = CascadeType.ALL)
private List<Student> students;
}
2
Answers
I’m also looking for a way to perform an action through another entity. I’m curious.
Let’s clarify some points regarding your design, especially considering the different user roles and relationships.
Inheritance Strategy
Using inheritance for your user types (e.g., Teacher, Student, Guardian, Manager) can be effective, but you need to choose an inheritance strategy that suits your needs. In JPA, you have several options:
Single Table Inheritance: All entities are stored in a single table, with a discriminator column to differentiate between them. This can simplify queries and relationships but may lead to sparse tables if entities have very different fields.
Joined Table Inheritance: Each entity is stored in its own table, but common fields are stored in a parent table. This approach can be cleaner and allows for more specific constraints per entity but may require more complex joins when querying.
Table per Class: Each class is stored in a separate table with no shared columns. This can lead to redundancy and is typically not recommended unless you have very specific needs.
Key Considerations
Approach for different Entities