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?