Hi,
I have a design issue in my code, I need to do a "find or create" an entity in massive concurrent code.
My goal is to rely on DB locking mechanism to handle this and avoid restarting the whole transaction in case of a concurrent issue (I have to handle errors...) :
Imagine a table Foo with :
ID PRIMARY
BAR UNIQUE
For concurrent insert on this table at SQL/JDBC level I do (pseudo code) :
Code:
Foo foo = foodao.findByBar(bar);
if(foo == null) {
// foobar does not exists or not committed.
foo = new Foo(bar);
try {
// If a second transaction have already inserted bar
// my insert is locked until other session commit or rollback
// Of course this insert cannot be delayed
foodao.save(foo);
// If the other transaction has rollbacked my insert is successfull
} catch(SQLException sqle) {
if(sqle.getErrorCode() == SQL_CODE_UNIQUE) {
// If other session has committed my bar
// then I will have to use this one and continue
// with mysql in this case I can read this value even if I'm in repeatable read transaction.
foo = foodao.findByBar(bar);
} else {
thow new MyException(sqle);
}
}
}
How can I do the same with hibernate and preferably JPA?
Will this be possible with the future Session.doWork(Work w) API?
SQLException thrown on the JDBC Connection offered will still invalidate my transaction even if catched?
Thank you.
David.