JPA and updating Embedded Units

Due to the company sensitive nature of the code, I’m having to create a similar example – hopefully none of the details are missed.

Using an example of having some information about Pets – such as the Pet Owner and their associated Pets – the database relationship being OneToMany (ie. an owner can have many pets, but a pet can only have one owner).

Therefore 2 database tables exist – namely ‘Owner’ and ‘Pet’. Owner essentially contains just the owners name, and then the Pets table consists of the owners name as the lookup field (not ideal, but this was the state of the database when I started), and then other characteristics such as Pet Name, age, etc…

By using Java Persistence, the java code generates 3 classes – Owner, Pet and PetPK – where PetPK essentially acts as a mapping table.

In the code I was trying to implement, what I wanted to do was update the Pet’s owner name. So for example if I owned 2 pets – there would be 2 PetPK entries of:

Owner Pet Name
Greg Bruno
Greg Tyson

I essentially want to change ‘Greg’ to ‘Joe’.

The code to perform the update follows, with an explanation about the ‘RemovalList’ following.

Owner theOwner = jpa.getOwner("Greg");
Collection<Pets> petsForRemoval = new ArrayList<Pets>();
Collection<Pets> pets = theOwner.getPetCollection();

for (Pets thePet : pets) {
   if (thePet.getPetsPK().getOwnerId().equalsIgnoreCase("Greg")) {

for (Pet removalPet : petsForRemoval) {


Without providing the removal list, the update appears to insert 2 new records for ‘Joe’, keeping the existing records for ‘Greg’ aswell – essentially ending up with 4 records. By doing the removal, only the records for ‘Joe’ are present in the database. There may be a cleaner solution for this, but I haven’t managed to find it yet.

Another important lesson I’ve learnt is not to use direct access to tidy up the database (certainly in an Oracle environment). The EntityManager appears to using a caching mechanism that is very difficult to clear down, and hence I’ve now got rogue data entries – and am waiting for a server reboot to see if these go away. FWIW  I didn’t experience this issue when testing the implementation with MySQL.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s