JPA OrderColumn Example

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.

Consider we want to maintain the persistent order of list when being inserted into the database and want to retrive the list in the order it was inserted. This JPA OrderColumn Example demonstrates how it can be done.

JPA OrderColumn Example:

Let us directly see what official javadoc says about OrderColumn

Specifies a column that is used to maintain the persistent order of a list. The persistence provider is responsible for maintaining the order upon retrieval and in the database. The persistence provider is responsible for updating the ordering upon flushing to the database to reflect any insertion, deletion, or reordering affecting the list.

Entities for JPA OrderColumn Example:

Consider we have Employee entity with fields idEmployee, firstName, lastName, salary and phones where phones is a list of strings. We can use ElementCollection to store strings. So entity will be as follows.

As we are using ElementCollection  in JPA OrderColumn Example, there will be a separate table to store phones. Database strucuture will be as below

JPA OrderColumn Example

 

Now that database and entities are created for JPA OrderColumn example, let us test it out,

After executing this, you can see that phone numbers are retrieved in the order they were insterted.

353745415
225765367
92573626726

I hope JPA OrderColumn example helped. Happy learning 🙂

Share Button

1 comment for “JPA OrderColumn Example

  1. Nagesh
    May 27, 2016 at 11:17 am

    Based on the above example, could you please let me know how we can delete data from employee_phones table. If we delete a specific record from employee_phones will re-ordering happen on phone_sequence column?
    Please let me know.

Leave a Reply

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