Search in sources :

Example 31 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project meveo by meveo-org.

the class BusinessService method findByEntityClassAndCode.

public BusinessEntity findByEntityClassAndCode(Class<?> clazz, String code) {
    QueryBuilder qb = new QueryBuilder(clazz, "be", null);
    qb.addCriterion("be.code", "=", code, true);
    try {
        return (BusinessEntity) qb.getQuery(getEntityManager()).getSingleResult();
    } catch (NoResultException e) {
        log.debug("No {} of code {} found", getEntityClass().getSimpleName(), code);
        return null;
    } catch (NonUniqueResultException e) {
        log.error("More than one entity of type {} with code {} found", entityClass, code);
        return null;
    }
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) QueryBuilder(org.meveo.commons.utils.QueryBuilder) NoResultException(javax.persistence.NoResultException) BusinessEntity(org.meveo.model.BusinessEntity)

Example 32 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project meveo by meveo-org.

the class BusinessService method findStartsWithCode.

/**
 * Find entity by code - match the beginning of code.
 *
 * @param codePrefix Beginning of code
 * @return A list of entities which code starts with a given value
 */
@SuppressWarnings("unchecked")
public List<P> findStartsWithCode(String codePrefix) {
    try {
        QueryBuilder qb = new QueryBuilder(getEntityClass(), "be");
        qb.like("be.code", codePrefix, QueryLikeStyleEnum.MATCH_BEGINNING, false);
        return (List<P>) qb.getQuery(getEntityManager()).getResultList();
    } catch (NoResultException ne) {
        return null;
    } catch (NonUniqueResultException nre) {
        return null;
    }
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) ArrayList(java.util.ArrayList) List(java.util.List) QueryBuilder(org.meveo.commons.utils.QueryBuilder) NoResultException(javax.persistence.NoResultException)

Example 33 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project meveo by meveo-org.

the class EntityExportImportService method findEntityByAttributes.

/**
 * Find an entity in target db by attributes
 *
 * @param entityToSave Entity to match
 * @return Entity found in target DB
 */
private IEntity findEntityByAttributes(IEntity entityToSave) {
    String[] attributes = exportIdMapping.get(entityToSave.getClass());
    if (attributes == null) {
        return null;
    }
    Map<String, Object> parameters = new HashMap<>();
    for (String attributeName : attributes) {
        Object attrValue;
        try {
            attrValue = getAttributeValue(entityToSave, attributeName);
            if (attrValue != null) {
                // search is parent entity, which does not exist yet.
                if (attrValue instanceof IEntity && ((IEntity) attrValue).isTransient()) {
                    return null;
                }
                parameters.put(attributeName, attrValue);
            }
        } catch (IllegalAccessException | IllegalArgumentException e) {
            throw new RuntimeException("Failed to access field " + entityToSave.getClass().getName() + "." + attributeName, e);
        }
    }
    // Construct a query to retrieve an entity by the attributes
    StringBuilder sql = new StringBuilder("select o from " + entityToSave.getClass().getName() + " o where ");
    boolean firstWhere = true;
    for (Entry<String, Object> param : parameters.entrySet()) {
        if (!firstWhere) {
            sql.append(" and ");
        }
        sql.append(String.format(" o.%s=:%s", param.getKey(), param.getKey().replace('.', '_')));
        firstWhere = false;
    }
    Query query = getEntityManagerForImport().createQuery(sql.toString());
    for (Entry<String, Object> param : parameters.entrySet()) {
        query.setParameter(param.getKey().replace('.', '_'), param.getValue());
    }
    try {
        IEntity entity = (IEntity) query.getSingleResult();
        log.trace("Found entity {} id={} with attributes {}. Entity will be updated.", entity.getClass().getName(), entity.getId(), parameters);
        return entity;
    } catch (NoResultException | NonUniqueResultException e) {
        log.debug("Entity {} not found matching attributes: {}, sql {}. Reason:{} Entity will be inserted.", entityToSave.getClass().getName(), parameters, sql, e.getClass().getName());
        return null;
    } catch (Exception e) {
        log.error("Failed to search for entity {} with attributes: {}, sql {}", entityToSave.getClass().getName(), parameters, sql, e);
        throw new RuntimeException(e);
    }
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) TypedQuery(javax.persistence.TypedQuery) Query(javax.persistence.Query) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) IEntity(org.meveo.model.IEntity) NoResultException(javax.persistence.NoResultException) NoResultException(javax.persistence.NoResultException) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) ELException(org.meveo.elresolver.ELException) NonUniqueResultException(javax.persistence.NonUniqueResultException)

Example 34 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project meveo by meveo-org.

the class IEntityExportIdentifierConverter method unmarshal.

/**
 * A lookup is done to DB using provided attributes to retrieve a reference to an entity
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
    Class expectedType = context.getRequiredType();
    // If unmarshaling a provider entity and were told to explicitly force it to be given provider
    if (forceToProvider != null && Provider.class.isAssignableFrom(expectedType)) {
        log.trace("Forcing provider to {}", forceToProvider);
        return forceToProvider;
    }
    // // This was a solution to large data amount processing with JPA transaction on each entity deserialisation, but it gives issues with references between the objects
    // EntityManager em = (EntityManager) context.get("em");
    String idValue = reader.getAttribute("id");
    // Obtain a reference to an entity by ID
    if (referenceFKById && idValue != null) {
        Object entity = em.find(expectedType, Long.parseLong(idValue));
        if (entity == null) {
            if (ignoreNotFoundFK) {
                log.debug("Entity " + expectedType.getName() + " not found and will be ignored. Lookup by id=" + idValue);
                return null;
            } else {
                throw new ImportFKNotFoundException(expectedType, idValue, null, null);
            }
        }
        return entity;
    // Obtain a reference to an entity by other attributes
    } else {
        Map<String, Object> parameters = new HashMap<String, Object>();
        final Iterator<String> it = reader.getAttributeNames();
        while (it.hasNext()) {
            final String attrName = it.next();
            String attrValue = reader.getAttribute(attrName);
            // Ignore ID field if looking up entity by non-id attributes
            if ("id".equals(attrName)) {
                continue;
            // Ignore system attributes
            } else if ("class".equals(attrName) || EntityExportImportService.REFERENCE_ID_ATTRIBUTE.equals(attrName)) {
                continue;
            // Other attributes are used as found
            } else {
                parameters.put(attrName, attrValue);
            }
        }
        // Probably the entity was exported as full in older versions and now trying to import as a reference
        if (parameters.isEmpty()) {
            log.debug("Entity {} not found. Reason: no parameters were found to query with. id={}. Will be passed to iEntityClassConverter.", expectedType.getName(), idValue);
            return context.convertAnother(context.currentObject(), expectedType, iEntityClassConverter);
        }
        // Construct a query to retrieve an entity by the attributes
        StringBuilder sql = new StringBuilder("select o from " + expectedType.getName() + " o where ");
        boolean firstWhere = true;
        for (Entry<String, Object> param : parameters.entrySet()) {
            if (!firstWhere) {
                sql.append(" and ");
            }
            if (StringUtils.isEmpty((String) param.getValue())) {
                sql.append(String.format(" %s is null", param.getKey()));
            } else {
                sql.append(String.format(" %s=:%s", param.getKey(), param.getKey().replace('.', '_')));
            }
            firstWhere = false;
        }
        Query query = em.createQuery(sql.toString());
        for (Entry<String, Object> param : parameters.entrySet()) {
            // Skip null values as they are taken care by "is null" sql clause
            if (StringUtils.isEmpty((String) param.getValue())) {
                continue;
            }
            Parameter<?> sqlParam = query.getParameter(param.getKey().replace('.', '_'));
            if (!sqlParam.getParameterType().isAssignableFrom(param.getValue().getClass())) {
                if (Enum.class.isAssignableFrom(sqlParam.getParameterType())) {
                    for (Object enumValue : sqlParam.getParameterType().getEnumConstants()) {
                        if (((Enum) enumValue).name().equals(param.getValue())) {
                            param.setValue(enumValue);
                        }
                    }
                } else if (Integer.class.isAssignableFrom(sqlParam.getParameterType())) {
                    param.setValue(Integer.parseInt((String) param.getValue()));
                } else if (Long.class.isAssignableFrom(sqlParam.getParameterType())) {
                    param.setValue(Long.parseLong((String) param.getValue()));
                } else if (Date.class.isAssignableFrom(sqlParam.getParameterType())) {
                    param.setValue(DateUtils.parseDateWithPattern((String) param.getValue(), DateUtils.DATE_TIME_PATTERN));
                }
            }
            query.setParameter(param.getKey().replace('.', '_'), param.getValue());
        }
        try {
            IEntity entity = (IEntity) query.getSingleResult();
            log.trace("Found entity {} id={} with attributes {}", entity.getClass().getName(), entity.getId(), parameters);
            // }
            return entity;
        } catch (NoResultException | NonUniqueResultException e) {
            if (ignoreNotFoundFK || exportImportConfig.isIgnoreFKToClass(expectedType)) {
                log.debug("Entity {} not found and will be ignored. Reason: {}. Lookup attributes: [id={}] {}", expectedType.getName(), e.getClass().getName(), idValue, parameters);
                return null;
            } else {
                throw new ImportFKNotFoundException(expectedType, idValue, parameters, e.getClass());
            }
        }
    }
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) Query(javax.persistence.Query) HashMap(java.util.HashMap) IEntity(org.meveo.model.IEntity) NoResultException(javax.persistence.NoResultException) Date(java.util.Date) Provider(org.meveo.model.crm.Provider)

Example 35 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project blaze-persistence by Blazebit.

the class HibernateExtendedQuerySupport method getSingleResult.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object getSingleResult(com.blazebit.persistence.spi.ServiceProvider serviceProvider, List<Query> participatingQueries, Query query, String sqlOverride, boolean queryPlanCacheEnabled) {
    EntityManager em = serviceProvider.getService(EntityManager.class);
    try {
        final List result = list(serviceProvider, em, participatingQueries, query, sqlOverride, queryPlanCacheEnabled);
        if (result.size() == 0) {
            NoResultException nre = new NoResultException("No entity found for query");
            hibernateAccess.handlePersistenceException(em, nre);
            throw nre;
        } else if (result.size() > 1) {
            final Set uniqueResult = new HashSet(result);
            if (uniqueResult.size() > 1) {
                NonUniqueResultException nure = new NonUniqueResultException("result returns more than one element");
                hibernateAccess.handlePersistenceException(em, nure);
                throw nure;
            } else {
                return uniqueResult.iterator().next();
            }
        } else {
            return result.get(0);
        }
    } catch (QueryExecutionRequestException he) {
        LOG.severe("Could not execute the following SQL query: " + sqlOverride);
        throw new IllegalStateException(he);
    } catch (TypeMismatchException e) {
        LOG.severe("Could not execute the following SQL query: " + sqlOverride);
        throw new IllegalArgumentException(e);
    } catch (HibernateException he) {
        LOG.severe("Could not execute the following SQL query: " + sqlOverride);
        throw hibernateAccess.convert(em, he);
    }
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) EntityManager(javax.persistence.EntityManager) Set(java.util.Set) HashSet(java.util.HashSet) QueryExecutionRequestException(org.hibernate.hql.internal.QueryExecutionRequestException) HibernateException(org.hibernate.HibernateException) TypeMismatchException(org.hibernate.TypeMismatchException) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) NoResultException(javax.persistence.NoResultException) HashSet(java.util.HashSet)

Aggregations

NonUniqueResultException (javax.persistence.NonUniqueResultException)67 NoResultException (javax.persistence.NoResultException)56 Query (javax.persistence.Query)30 EntityManager (javax.persistence.EntityManager)11 List (java.util.List)7 PersistenceException (javax.persistence.PersistenceException)6 Collection (java.util.Collection)5 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)5 QueryBuilder (org.meveo.commons.utils.QueryBuilder)5 IOException (java.io.IOException)4 Date (java.util.Date)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 EntityExistsException (javax.persistence.EntityExistsException)3 EntityNotFoundException (javax.persistence.EntityNotFoundException)3 OptimisticLockException (javax.persistence.OptimisticLockException)3 TransactionRequiredException (javax.persistence.TransactionRequiredException)3 TypedQuery (javax.persistence.TypedQuery)3 WebResource (org.asqatasun.entity.subject.WebResource)3 PopulationDataCriteria (de.symeda.sormas.api.infrastructure.PopulationDataCriteria)2