Primary and secondary table with JPA

It‘s the third time I‘ve been asked if in JPA you can persist the attributes of your entity in several tables. The answer is yes. It has a performance impact (each simple query will use joins) but it can be very helpful when you need to map your objects into an existing database.

Here is an example of an Address entity that persist its data into a primary table (t_address) as well as two secondary tables (t_city and t_country). The primary table can be customized with the Table annotation and the secondary with SecondaryTable or SecondaryTables (with an 's') if more than one. Then it's just a matter of explicitly using the Column annotation on the attributes you want to persist in the secondary tables (@Column(table=“t_city”) would tell JPA to persist this particular attribute into the t_city table). By default the attributes are persisted in the primary.

@Table(name = "t_address")
public class FirstTable {

    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String street1;
    private String street2;

    private String city;
    private String state;
    private String zipcode;

    private String country;

As a result of that, you will get three tables with the following columns :

  • t_address : id, street1, street2
  • t_city : id, city, state, zipcode
  • t_country : id, country

Notice that the id is replicated in each table.

Categories: Java

1 Comment »

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s