-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: saveOrUpdate behavior for assigned ID in a multithread case
PostPosted: Fri Dec 21, 2012 2:26 pm 
Newbie

Joined: Thu Dec 20, 2012 11:40 pm
Posts: 1
Let's say we have the following model:

Code:
@Entity
  @Table(name = "PIG",
      uniqueConstraints = {
          @UniqueConstraint(columnNames = {"WEIGHT"})
      }
  )
  public class Pig {
      @Id
      @Column(name = "ID", nullable = false, updatable = false)
      private Long id = null;

      @Column(name = "WEIGHT", nullable = false, updatable = false)
      private Long weight;
    
     ...
}


and the following method:

Code:
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public Pig createPig(final long weight) {
   final String query = "from Pig p order by p.id desc";
        Pig pig = (Pig) getSession().createQuery(query)
                 .setMaxResults(1)
                 .uniqueResult();
   long nextPigId = SENTINAL_PIG_ID;
   if (pig != null) {
            nextPigId = pig.getId() + 1;
   }
   
   final newPig = new Pig(nextPigId, weight);
   
   getSession().saveOrUpdate(newPig);
   
   return newPig;
}


Now suppose there is already one row in DB:

Quote:
| ID | WEIGHT |
| 1 | 100 |


and try the following:

In thread one, call createPig(500) but only to stop the thread just after it has loaded the old pig from DB and before calculating the new id. Then execute thread two, which calls createPig(1000) and let it finish.

As expected, the DB now looks like

Quote:
| ID | WEIGHT |
| 1 | 100 |
| 2 | 1000 |


And then resume the first thread. One would expect to see some kind of exception. But no, nothing happened. The code just returns the newPig with id=2, weight=500 and no exception thrown. And the DB still looks like above.

It seems 'saveOrUpdate' in thread one here only 're-associate' the newPig object but without actually trying to save/update it. Is this expected or did I miss anything?


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.