How to Create Two Entities in JPA with the Same Database Table
A basic concept of JPA is that for each database table we create an entity. However, JPA can do much more, and in this article, I will show how to create two entities in JPA that share the same database table.
Scenario
We have a system which contains a table called bank-account, which contains some fields related to a checking account. This table is mapped to a java class called CheckingAccount, which is annotated with @Entity.
The CheckingAccount entity class code will be like this (lets use lombok to reduce the boilerplate code):
@Entity
@Table(name = "bank-account")
@Getter
@Setter
@NoArgsConstructor
public class CheckingAccount {
@Id
private int id;
private String name;
@Column("start-date")
private LocalDate startDate;
}
Remarks:
- The Entity annotation identifies that it is managed by the JPA.
- The Table annotation identifies the properties of the database table; in this case, we set the name of the database table.
- The start-date column of the database table was mapped to the startDate attribute in the Java class via Column annotation.