Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JPA Weird Behavior

 
nitin pai
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As per the JPA specs, the application must not attempt to change the primary key of an Entity. But it might be a case where in I need to update an entities' primary key.

Take the use case of a bank who later on decides to change the ID's of all the customers due to a merger with another bank so as to form global customer ID's.

I tried such a case in my project and I get this error.

The attribute [..] of class [....] is mapped to a primary key column in the database. Updates are not allowed.


In such a case what can be done if you are using JPA?
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had to do something similar. I felt it a total kludge, but this is what I did:

Start a transaction, load the entity, evict the entity and hold onto the detached instance, delete the entity, null the primary keys of the evicted instance (or you could just give it a new id), save the detached instance. The instance will be saved with a new primary key, but it's old data.

There are landmines here like crazy. Lazily loaded collections won't get saved, and will be lost.

I'd suggest an ETL tool like DataStage would be better suited such an activity, but in a little proof of concept app, I got it to work. Having said that, using JPA properly, and getting it to do what you want are two different things. If this is a serious application, make sure that you're doing both: using it properly, and getting it to do what you want it to do.

-Cameron McKenzie
 
nitin pai
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Cameron,

I solved the problem by an alternative. I think you chose a complicated route or maybe it was required for your situation.

The solution to this problem is to use JPQL. JPA won't allow you to use setters which are meant for primary keys, but it will allow you to update the primary key using JPQL query.

After I got that error, I used an update statement and did a Query.executeUpdate(). The primary key got updated.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic