My models have primarykey(autogeneratedID) and a unique code . Unique code is not primarykey.
So, when user sends entity with uniqueCode, I need to check the database whether that particular uniquecode entry is existing or not. If, existing I need to update Else, I need to save.
My code;
Code:
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void insertOrUpdate(T entity) {
try {
List<T> resultList = null;
if (entity.getCode() != null) {
resultList = criteria.add(Restrictions.eq("code", entity.getCode())).list()
}
if (entity.getId() != null) {
resultList = criteria.add(Restrictions.eq("code", entity.getId())).list()
}
if (resultList != null && !resultList.isEmpty()) {
T entity2 = resultList.get(0);
entity.setId(entity2.getId());
session.merge(entity); //PROBLEM*****
} else {
session.save(entity);
}
} catch (OptimisticLockException e) {
session.saveOrUpdate(entity);
} catch (Exception e) {
log.error("Save or Update fails, ", e);
}
}
If I use, session.saveOrUpdate(entity); instead of session.merge(entity); I get following exception;
Quote:
org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : xx
If I use session.merge(entity)` I get
Quote:
avax.persistence.OptimisticLockException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
How can I overcome these exceptions? Im trying to saveOrupdate for a single row. There is no concurrent requests. Only single request.
I create session like; (container managed session)
Code:
public Session getSession() {
if (session == null || !session.isOpen()) {
session = getEntityManager().unwrap(Session.class);
}
return session;
}