Checking for duplicates before EntityHome.update() fails
dhinojosa Apr 2, 2009 9:17 PMI can't believe I have encountered this yet.
I have a unique constraint on a field called 'value' in an Entity called 'Assumption'. I can successfully determine if the a duplicate is being entered for persist().
@SuppressWarnings({"UnusedAssignment"}) @Override @Transactional public String persist() { try { Query query = getEntityManager().createQuery("SELECT a from Assumption a where a.value = :value"); query.setParameter("value", getInstance().getValue()); query.getSingleResult(); getStatusMessages().addFromResourceBundleOrDefault( StatusMessage.Severity.ERROR, "assumptionNotUnique", "The assumption \'{0}\' has already been entered", getInstance().getValue()); return "failure"; } catch (NoResultException nre) { getInstance().setCreatedDate(calendar); getInstance().setUpdatedDate(calendar); return super.persist(); } }
but when I use similar logic for update() I get an exception, and it is perplexing.
@Override @Transactional public String update() { try { Query query = getEntityManager().createQuery("SELECT a from Assumption a where a.value = :value"); query.setParameter("value", getInstance().getValue()); Assumption assumption = (Assumption) query.getSingleResult(); if (!(getInstance().getId().equals(assumption.getId()))) { getStatusMessages().addFromResourceBundleOrDefault( StatusMessage.Severity.ERROR, "assumptionNotUnique", "The assumption \'{0}\' has already been entered", getInstance().getValue()); return "failure"; } getInstance().setUpdatedDate(calendar); return super.update(); } catch (NoResultException nre) { getInstance().setUpdatedDate(calendar); return super.update(); } catch (RuntimeException re) { re.printStackTrace(); return "failure"; } }
The issue is that Assumption assumption = (Assumption) query.getSingleResult(); is not running nor does it provide any message as to why it doesn't. Any ideas?