Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in saveOrUpdate() method in hibernate

 
Kunal Lakhani
Ranch Hand
Posts: 622
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am working on a hibernate project.

Before inserting any record i have to check whether the record is present on DB. If present i have to update it, and if not, save it. On updating it should return 1, an int, and 0 on saving. Based on this return value, it performs some additional functions.


Here is the code


The problem is that even on inserting a new record, it goes to else if block containing the saveOrUpdate().
What is the mistake here?
 
Kunal Lakhani
Ranch Hand
Posts: 622
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No reply yet
 
Kunal Lakhani
Ranch Hand
Posts: 622
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When i am using get() instead of load(), it saves new entity. But when i run the different code for Editing, and it uses the same DAO code as mentioned earlier, it throws following exception

 
Hemant Thard
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kunal ,

The problem is because of this code


try copying all changes to sp and saveorUpdate it.




 
Kunal Lakhani
Ranch Hand
Posts: 622
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hemant Thard, it works. Thanks.

But, i really don't know why the code given by me doesn't works.
 
Hemant Thard
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kunal Lakhani wrote:Hemant Thard, it works. Thanks.

But, i really don't know why the code given by me doesn't works.


The reason is that you cannot have 2 different object having same identifier in hibernate persistence context.

This is what the exception tells you.

NonUniqueObjectException: a different object with the same identifier value was already associated with the session:
 
Kunal Lakhani
Ranch Hand
Posts: 622
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Hemant Thard
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic