1

How can I remove an object from hibernate session? In my code I am fetching one list from the DB and searching if the user entered data is already there in the DB. If it is there I am overwriting it. Else I am creating a new object and saving it. But the jboss shows error that there are two objects in session. As far as i guess one object is the object that iterates through the list and other is the one newly created for saving the data.

for(Allocation al: allocatelist){
    if(al.getDate().compareTo(dt)==0){
          al.setAllocated(gpsz);
          getManager().save(al);
          flag=1;
          break;
    {
{

If the above condition fails then am creating and new object and saving it. So is there any way by which I can remove this object "al"? I don't have merger or update methods I have tried "evict()" also but its of no use. The else block

 Allocation allocate = new Allocation();
allocate = filldata(allocate, dataMap,i); 
   getManager().save(allocate);   
 filldata() fills the inputs into the object.`
  • Possible Duplicate: http://stackoverflow.com/questions/3288838/remove-object-from-session-in-hibernate – bchetty Feb 21 '12 at 13:03
  • What's the message and stack trace of the exception? – JB Nizet Feb 21 '12 at 13:07
  • 1
    If the Allocation object is managed by Hibernate, then there is no need for you to call "getManager().save(al);" because hibernate detects that the object is changed and it will save it. – Sajan Chandran Feb 21 '12 at 13:11
  • @SajanChandran: this should be an answer rather than a comment. Make it an answer, elaborate a bit more on what save means and why you can't save an already existing attached entity, and I'll upvote it. – JB Nizet Feb 21 '12 at 13:17
  • @SajanChandran Yes it does so. But when the condition fails hibernate does not save the object. So duplicate remains –  Feb 21 '12 at 13:19
  • Can u post your else block ? the place you save the new object# – Sajan Chandran Feb 21 '12 at 13:29
  • Allocation allocate = new Allocation(); allocate = filldata(allocate, dataMap,i); getManager().save(allocate); filldata() fills the inputs into the object. –  Feb 21 '12 at 13:33
  • The Allocation object you create in your else block, by any chance have the same identifier as any of the allocation object from hibernate. – Sajan Chandran Feb 21 '12 at 13:45
  • Any reason why you can not use session.saveOrUpdate()? – ManuPK Feb 21 '12 at 15:57

1 Answers1

0

If the Allocation object is managed by Hibernate, then there is no need for you to call getManager().save(al), because hibernate detects that the object is changed and it will automatically update the database.

Sajan Chandran
  • 11,287
  • 3
  • 29
  • 38