Avihai (2) [Avatar] Offline

First of all I want to thank you for your book it is a pleasure to read a book that give you such a wide perspective.

I have a difficult problem that I can’t solve, maybe you can help.

Let’s say I have a buyer obj that has a reference to book collection. The book collection is a set of books represented by unique hash.

fk to Book collection.

hashId (uniq , calculated by the books that it represents)
set of books.


Books and BookCollection have many to many relationships.

Save a Buyer:

//the if needed because if it already exists and I don’t attach it hibernate will call to //update on it and on the book that it contain
if (session.get(CriteriaDictionaryImpl.class, new Long(hashKey)) != null) {
Buyer.setBooksCollection(session.get(CriteriaDictionaryImpl.class, new Long(hashKey)) );

The hashId it the pk for BooksCollection and for Books (it is assign by the application).

My application is multi threaded. I use web service to save Buyer so each request has its own session.

I have Books and BooksCollection in the second level cache.

The problem is that when two threded with different buyer but the same books collection try to save at the same time i get:
Exception - java.sql.SQLException: Duplicate entry '1075191317' for key 1

I close the session and try to save (The same logic like above) the Buyer again , but failed with (the BooksCollection save by the first thread so in this time I take it from the DB ) :
org.hibernate.StaleStateException: Unexpected row count: 0 expected: 1

** - the reason I create BooksCollection is that I don’t want to save the same books again for each buyer. My goal is to have only one instance of book in the DB.
*** - The reason that I use hashId and not incremental ID for the Books is because I don’t want situation like this:
Id- 1, name – hibernate
Id -2 , name – hibernate

Thank you