JPA AttributeOverride annotation.

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello, We have seen about embeddable objects in previous article. This will deal with shortcomings and how to overcome them with jpa AttributeOverride annotation.

JPA AttributeOverride annotation.

Consider two entities, Person and Office . Both entities have fields which represent the their address. In previous article we have used embedded Address for Person entity. As embeddable objects can be re-used, we want to use them for Office entity also. Person and Office are represented in database as follows.

entities

We want to reuse Address embedded object for Office entity. In case of Person table, the column names matched the field names of Address i.e. area, city and pincode. But for Office , the address is represented in the columns landmark, city and postal_code.

So how can we map address fields to these columns?

JPA AttributeOverride annotation comes to the rescue. This is what javadoc says about it.

Used to override the mapping of a Basic (whether explicit or default) property or field or Id property or field.

For Person entity, the field names of Address match with column names of person table. Hence we do not need to override anything

For mapping address to Office table, we need to

  • map area attribute of Address to landmark column of Office.
  • map pincode attribute of Address to postal_code column of Office.
  • map city attribute of Address to city column of Office.

You can see that the name of attribute city matches to city column on Office table. Hence there is no need to override it. We just need to map area and pincode with the help of jpa attributeoverride annotation.

So Office entity becomes,

Things to notice here,

Persistence Unit,

 

You can test it out using code,

After running this, you will notice a new record for person and office tables is inserted in database with same address.

I hope this articled helped understand how to map embedded object fields to database table columns with the help of jpa attributeoverride annotation.

Please feel free to comment and suggest improvements.

 

References for further study :

 

 

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Leave a Reply

Your email address will not be published. Required fields are marked *