Reputation: 1780
When both Thread1
and Thread2
are running, is it possible to prevent two Foo
objects being saved to the database?
Thread1 {
Foo foo = dao.getFoo("bar");
if(foo == null) {
foo = new Foo("bar");
dao.save(foo);
}
}
Thread2 {
Foo foo = dao.getFoo("bar");
if(foo == null) {
foo = new Foo("bar");
dao.save(foo);
}
}
Upvotes: 2
Views: 3789
Reputation: 8068
Yes. Use the database unique constraint feature and hibernates concurrency control mechanism which is based on version numbers. Have a look here.
For insertion you need to use the database unique constraint feature. For concurrent modification you may use hibernates optimistic locking concurrency control.
The unique constraint will prevent two threads to insert a record having the same values for a set (even only one) of columns. Hibernates concurrency control will increase the version number of an existing record when committing an update transaction, but only if the record in the database has still the same version number read when the transaction begun. This will prevent two transactions from successfully commiting changes, based on a record having the same version number.
Upvotes: 7