user1847624
user1847624

Reputation: 21

How Can I have one parent ENTITY and many types of child ENTITIES in JPA?

I am trying to design my ENTITY CLASSES using JPA annotations.

What I am trying to do is as follows :

A USER table with
id, ***email, password, activation_key, active, role***

and many TYPES OF USER table with for eg.
STUDENT_TABLE
USER_ID FirstName LastName Company Address etc

MENTOR
USER_ID FirstName LastNAme DOB Department etc

When USER will register depending o their ROLE they will be sotred in two tables (USER,MENTOR/STUDENT)

When they will log in , the ManagedBean will look into the UESR table to verify the authentication.

I tired to use @OneToOne but It just works with two tables.

I would really appreciate if any1 can help!!

Thanks

Upvotes: 1

Views: 298

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

If I understand correctly, what you want is an inheritance relationship:

@Entity
@Inheritance(strategy = JOINED)
public abstract class User { ... }

@Entity
public class Student extends User { ... }

@Entity
public class Mentor extends User { ... }

The JOINED strategy tells JPA that the fields in the User class are stored in a table (USER), and that each subclass persists its own field in its own table (STUDENT and MENTOR), with a join column used to refer to the USER table ID.

Upvotes: 3

Related Questions