I want to store unique entities with their hashes. An entity consists of a generated id and an hash value which must be unique. I do this with this code:
@Stateless
@LocalBean
public class srvcEntity {
@PersistenceContext(unitName = "mine")
private EntityManager em;
private Long save(byte[hash]) {
List<Entity> list = Entity.findByHash(hash, em); // using TypedQuery.getResultList()
if (list != null && list.size() > 0) {
entityId = list.get(0).getId();
} else {
Entity e = Entity.save(hash, em); // using em.persist()
if (e != null) {
entityId = e.getId();
}
}
return entityId;
}
}
This works very well till I get a lot of entities to store simultaneously. Then a race condition can lead to the sitation that at the time of read no entity with the given hash can be found but at save time I get a ConstraintViolationException for a duplicate hash.
Because my code exists in a bean with container based transactions, I simply can not read again after the save has failed.
How can I resolve this race condition?