Example usage for javax.persistence NonUniqueResultException NonUniqueResultException

List of usage examples for javax.persistence NonUniqueResultException NonUniqueResultException

Introduction

In this page you can find the example usage for javax.persistence NonUniqueResultException NonUniqueResultException.

Prototype

public NonUniqueResultException(String message) 

Source Link

Document

Constructs a new NonUniqueResultException exception with the specified detail message.

Usage

From source file:org.cagrid.identifiers.namingauthority.dao.AbstractDao.java

public T getByExample(final T sample) {
    T result = null;//from ww w . j  a v a 2 s  .c  om
    List<T> results = searchByExample(sample, false);
    if (results.size() > 1) {
        throw new NonUniqueResultException(
                "Found " + results.size() + " " + sample.getClass().getName() + " objects.");
    } else if (results.size() == 1) {
        result = results.get(0);
    }
    return result;
}

From source file:py.una.pol.karaku.dao.util.MainInstanceHelper.java

static Object fetchAttribute(final Session session, final String hql, final MainInstance principal,
        final Object parent) {

    if (!session.isOpen()) {
        throw new org.hibernate.LazyInitializationException(
                "Session is closed, failed to load Main instance " + principal.path());
    }/*from w  w  w  . j a v  a2s . co m*/
    Query query = session.createQuery(hql);
    query.setMaxResults(2);
    query.setParameter("value", principal.value());
    query.setParameter("mainEntity", parent);
    List<Object> list = query.list();
    if (list == null || list.isEmpty()) {
        return null;
    }
    if (list.size() > 1) {
        throw new NonUniqueResultException("Attribute " + principal.attribute() + " has more than 1 principal");
    }
    return list.get(0);
}

From source file:com.tapas.evidence.repository.data.CrudRepositoryImpl.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private T readTenantAware(ID id) {
    final T entry;
    final Long tenantId = ((EvidenceUserDetails) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal()).getTenantId();
    final Query query = this.entityManager
            .createQuery("from " + this.entityClass.getName() + " where tenant.id = :tenantId");
    query.setParameter("tenantId", tenantId);
    final List resultList = query.getResultList();
    if (resultList.size() == 1) {
        entry = (T) resultList.get(0);//from  w  w  w  .j a v a 2  s.c  o m
    } else if (resultList.size() > 1) {
        throw new NonUniqueResultException(
                "Non unique entity for class " + this.entityClass + " with id " + id + "!");
    } else {
        entry = null;
    }
    return entry;
}

From source file:org.querybyexample.jpa.GenericRepository.java

/**
 * We request at most 2, if there's more than one then we throw a
 * {@link NonUniqueResultException}//from  w  w w  .  j a va  2 s . c  o  m
 *
 * @throws NonUniqueResultException
 */
@Transactional(readOnly = true)
public E findUniqueOrNone(E entity, SearchParameters sp) {
    // this code is an optimization to prevent using a count
    sp.setFirst(0);
    sp.setMaxResults(2);
    List<E> results = find(entity, sp);

    if (results == null || results.isEmpty()) {
        return null;
    } else if (results.size() > 1) {
        throw new NonUniqueResultException(
                "Developper: You expected 1 result but we found more ! sample: " + entity);
    } else {
        return results.iterator().next();
    }
}

From source file:org.dhatim.persistence.EntityLocator.java

@SuppressWarnings("unchecked")
public void lookup(ExecutionContext executionContext, Fragment source) {
    final DaoRegister emr = PersistenceUtil.getDAORegister(executionContext);

    Object dao = null;//from   w  w w  .  j av a  2s. c om
    try {
        if (daoName == null) {
            dao = emr.getDefaultDao();
        } else {
            dao = emr.getDao(daoName);
        }

        if (dao == null) {
            throw new IllegalStateException(
                    "The DAO register returned null while getting the DAO '" + daoName + "'");
        }

        Object result = lookup(dao, executionContext);

        if (result != null && uniqueResult == true) {
            if (result instanceof Collection) {
                Collection<Object> resultCollection = (Collection<Object>) result;

                if (resultCollection.size() == 0) {
                    result = null;
                } else if (resultCollection.size() == 1) {
                    for (Object value : resultCollection) {
                        result = value;
                    }
                } else {
                    String exception;
                    if (daoName == null) {
                        exception = "The " + getDaoNameFromAdapter(dao) + " DAO";
                    } else {
                        exception = "The DAO '" + daoName + "'";
                    }
                    exception += " returned multiple results for the ";
                    if (lookupName != null) {
                        exception += "lookup '" + lookupName + "'";
                    } else {
                        exception += "query '" + query + "'";
                    }
                    throw new NonUniqueResultException(exception);
                }

            } else {
                throw new SmooksConfigurationException(
                        "The returned result doesn't implement the '" + Collection.class.getName()
                                + "' interface " + "and there for the unique result check can't be done.");
            }
        }

        if (result == null && onNoResult == OnNoResult.EXCEPTION) {
            String exception;
            if (daoName == null) {
                exception = "The " + getDaoNameFromAdapter(dao) + " DAO";
            } else {
                exception = "The DAO '" + daoName + "'";
            }
            exception += " returned no results for lookup ";
            if (lookupName != null) {
                exception += "lookup '" + query + "'";
            } else {
                exception += "query '" + query + "'";
            }
            throw new NoLookupResultException(exception);
        }

        BeanContext beanContext = executionContext.getBeanContext();

        if (result == null) {
            beanContext.removeBean(beanId, source);
        } else {
            beanContext.addBean(beanId, result, source);
        }
    } finally {
        if (dao != null) {
            emr.returnDao(dao);
        }
    }
}

From source file:org.kuali.rice.kim.impl.role.RoleServiceBase.java

protected RoleBo getRoleBoByName(String namespaceCode, String roleName) {
    if (StringUtils.isBlank(namespaceCode) || StringUtils.isBlank(roleName)) {
        return null;
    }/*from  w  w  w.  j a  va 2 s .c  om*/
    Map<String, Object> criteria = new HashMap<String, Object>(3);
    criteria.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode);
    criteria.put(KimConstants.UniqueKeyConstants.NAME, roleName);
    criteria.put(KRADPropertyConstants.ACTIVE, Boolean.TRUE);
    QueryResults<RoleBo> results = getDataObjectService().findMatching(RoleBo.class,
            QueryByCriteria.Builder.andAttributes(criteria).build());
    if (results.getResults().isEmpty()) {
        return null;
    } else if (results.getResults().size() > 1) {
        throw new NonUniqueResultException("Finding a role by name should return a unique role, "
                + "but encountered multiple. namespaceCode='" + namespaceCode + "', name='" + roleName + "'");
    }
    return results.getResults().get(0);
}

From source file:org.kuali.rice.kim.impl.role.RoleServiceBase.java

protected RoleBoLite getRoleBoLiteByName(String namespaceCode, String roleName) {
    if (StringUtils.isBlank(namespaceCode) || StringUtils.isBlank(roleName)) {
        return null;
    }//from   w ww .  j a v a 2s .  c o m
    Map<String, Object> criteria = new HashMap<String, Object>(3);
    criteria.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode);
    criteria.put(KimConstants.UniqueKeyConstants.NAME, roleName);
    criteria.put(KRADPropertyConstants.ACTIVE, Boolean.TRUE);
    QueryResults<RoleBoLite> results = getDataObjectService().findMatching(RoleBoLite.class,
            QueryByCriteria.Builder.andAttributes(criteria).build());
    if (results.getResults().isEmpty()) {
        return null;
    } else if (results.getResults().size() > 1) {
        throw new NonUniqueResultException("Finding a role by name should return a unique role, "
                + "but encountered multiple. namespaceCode='" + namespaceCode + "', name='" + roleName + "'");
    }
    return results.getResults().get(0);
}

From source file:org.kuali.rice.krad.data.jpa.JpaPersistenceProvider.java

/**
 * {@inheritDoc}/*ww w .j  a v a  2 s . c o m*/
 */
@Override
@Transactional(readOnly = true)
public <T> T find(final Class<T> type, final Object id) {
    return doWithExceptionTranslation(new Callable<T>() {
        @Override
        public T call() {
            if (id instanceof CompoundKey) {
                QueryResults<T> results = findMatching(type,
                        QueryByCriteria.Builder.andAttributes(((CompoundKey) id).getKeys()).build());
                if (results.getResults().size() > 1) {
                    throw new NonUniqueResultException("Error Compound Key: " + id + " on class "
                            + type.getName() + " returned more than one row.");
                }
                if (!results.getResults().isEmpty()) {
                    return results.getResults().get(0);
                }
                return null;
            } else {
                return sharedEntityManager.find(type, id);
            }
        }
    });
}

From source file:org.sonar.jpa.session.JpaDatabaseSession.java

/**
 * @return the result or <code>defaultValue</code>, if not found
 * @throws NonUniqueResultException if more than one result
 *//*ww  w  .j a v a 2 s .  co m*/
@Override
public <T> T getSingleResult(Query query, T defaultValue) {
    /*
     * See http://jira.codehaus.org/browse/SONAR-2225
     * By default Hibernate throws NonUniqueResultException without meaningful information about context,
     * so we improve it here by adding all results in error message.
     * Note that in some rare situations we can receive too many results, which may lead to OOME,
     * but actually it will mean that database is corrupted as we don't expect more than one result
     * and in fact org.hibernate.ejb.QueryImpl#getSingleResult() anyway does loading of several results under the hood.
     */
    List<T> result = query.getResultList();

    if (result.size() == 1) {
        return result.get(0);

    } else if (result.isEmpty()) {
        return defaultValue;

    } else {
        Set<T> uniqueResult = new HashSet<T>(result);
        if (uniqueResult.size() > 1) {
            throw new NonUniqueResultException("Expected single result, but got : " + result.toString());
        } else {
            return uniqueResult.iterator().next();
        }
    }
}

From source file:org.sonar.jpa.session.JpaDatabaseSession.java

/**
 * @return the result or <code>null</code>, if not found
 * @throws NonUniqueResultException if more than one result
 *//*from w w w.  java2s . c  om*/
@Override
public <T> T getSingleResult(Class<T> entityClass, Object... criterias) {
    try {
        return getSingleResult(getQueryForCriterias(entityClass, true, criterias), (T) null);

    } catch (NonUniqueResultException ex) {
        NonUniqueResultException e = new NonUniqueResultException("Expected single result for entitiy "
                + entityClass.getSimpleName() + " with criterias : " + StringUtils.join(criterias, ","));
        throw (NonUniqueResultException) e.initCause(ex);
    }
}