Map multiple JPA Entities to one database table with hibernate

Tram Ho


In many projects, you may have problems mapping multiple entities into a single table. So how to accomplish this with JPA. In this article I will introduce how to map multiple entities into one table. Using multiple entities can help speed read and write operations to the database. In this article I will use the PostgreSQL database


Here I have a Bill define table as below:

Here I have the information of 1 bill as above, now I will mapping this bill with 2 entities BillEntity and TransactionEntity, firstly I define an entity called BaseBill:




BaseBill is an abstract class. The abstract BaseBill class uses anotation @MappedSuperclass so that the BillEntity and TransactionEntity classes can inherit the BaseBill attributes. To learn more about @MappedSuperclass , you can refer here .

OK, now we will try to manipulate the database to see how. Here I will implement 2 functions to create BillEntity and TransactionEntity:

Create BillEntity:

Result log:

create TransactionEntity

Result log:

So we see in the create TransactionEntity method, the transaction_date has also been inserted into the database. Result of database:

In abstract BaseBill class we have defined company_id as @NaturalId . So we can fetch data using NaturalId . Define 1 method to get via naturalId:



So, through the above article, I introduced how to map multiple entities with 1 table in the database, hoping this article will be helpful to everyone.

Share the news now

Source : Viblo