Search in sources :

Example 26 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project civiform by seattle-uat.

the class VersionRepository method getDraftVersion.

/**
 * Get the current draft version. Creates it if one does not exist.
 */
public Version getDraftVersion() {
    Optional<Version> version = database.find(Version.class).where().eq("lifecycle_stage", LifecycleStage.DRAFT).findOneOrEmpty();
    if (version.isPresent()) {
        return version.get();
    } else {
        // Suspends any existing thread-local transaction if one exists.
        // This method is often called by two portions of the same outer transaction,
        // microseconds apart.  It's extremely important that there only ever be one
        // draft version, so we need the highest transaction isolation level -
        // `SERIALIZABLE` means that the two transactions run as if each transaction
        // was the only transaction running on the whole database.  That is, if any
        // other code accesses these rows or executes any query which would modify them,
        // the transaction is rolled back (a RollbackException is thrown).  We
        // are forced to retry.  This is expensive in relative terms, but new drafts
        // are very rare.  It is unlikely this will represent a real performance penalty
        // for any applicant - or even any admin, really.
        Transaction transaction = database.beginTransaction(TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE));
        try {
            Version newDraftVersion = new Version(LifecycleStage.DRAFT);
            database.insert(newDraftVersion);
            database.find(Version.class).forUpdate().where().eq("lifecycle_stage", LifecycleStage.DRAFT).findOne();
            transaction.commit();
            return newDraftVersion;
        } catch (NonUniqueResultException | SerializableConflictException | RollbackException e) {
            transaction.rollback(e);
            // We must end the transaction here since we are going to recurse and try again.
            // We cannot have this transaction on the thread-local transaction stack when that
            // happens.
            transaction.end();
            return getDraftVersion();
        } finally {
            // This may come after a prior call to `transaction.end` in the event of a
            // precondition failure - this is okay, since it a double-call to `end` on
            // a particular transaction.  Only double calls to database.endTransaction
            // must be avoided.
            transaction.end();
        }
    }
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) Transaction(io.ebean.Transaction) Version(models.Version) SerializableConflictException(io.ebean.SerializableConflictException) RollbackException(javax.persistence.RollbackException)

Example 27 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project container by OpenTOSCA.

the class CoreEndpointServiceImpl method existsWSDLEndpoint.

/**
 * Helper method to check if a given WSDLEndpoint is already stored in the database
 *
 * @param endpoint to look for
 * @return true, if the Endpoint already exists.
 */
private boolean existsWSDLEndpoint(final WSDLEndpoint endpoint) {
    TypedQuery<WSDLEndpoint> findQuery = em.createQuery("SELECT e from WSDLEndpoint e where e.PortType = :portType " + "and e.csarId = :csarId and e.managingContainer = :managingContainer " + "and e.serviceTemplateInstanceID = :serviceTemplateInstanceID and e.PlanId = :planId", WSDLEndpoint.class);
    findQuery.setParameter("portType", endpoint.getPortType());
    findQuery.setParameter("csarId", endpoint.getCsarId());
    findQuery.setParameter("managingContainer", endpoint.getManagingContainer());
    findQuery.setParameter("serviceTemplateInstanceID", endpoint.getServiceTemplateInstanceID());
    findQuery.setParameter("planId", endpoint.getPlanId());
    try {
        @SuppressWarnings("unused") WSDLEndpoint dbResult = findQuery.getSingleResult();
        return true;
    } catch (NoResultException | NonUniqueResultException umm) {
        // maybe return true if result is not unique?
        return false;
    }
}
Also used : WSDLEndpoint(org.opentosca.container.core.model.endpoint.wsdl.WSDLEndpoint) NonUniqueResultException(javax.persistence.NonUniqueResultException) NoResultException(javax.persistence.NoResultException)

Example 28 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project shopizer by shopizer-ecommerce.

the class ProductRepositoryImpl method getProductForLocale.

@Override
public Product getProductForLocale(long productId, Language language, Locale locale) {
    List regionList = new ArrayList();
    regionList.add("*");
    regionList.add(locale.getCountry());
    StringBuilder qs = new StringBuilder();
    qs.append("select distinct p from Product as p ");
    qs.append("join fetch p.availabilities pa ");
    qs.append("join fetch p.descriptions pd ");
    qs.append("join fetch p.merchantStore pm ");
    qs.append("left join fetch pa.prices pap ");
    qs.append("left join fetch pap.descriptions papd ");
    // images
    qs.append("left join fetch p.images images ");
    // options
    qs.append("left join fetch p.attributes pattr ");
    qs.append("left join fetch pattr.productOption po ");
    qs.append("left join fetch po.descriptions pod ");
    qs.append("left join fetch pattr.productOptionValue pov ");
    qs.append("left join fetch pov.descriptions povd ");
    qs.append("left join fetch p.relationships pr ");
    // other lefts
    qs.append("left join fetch p.manufacturer manuf ");
    qs.append("left join fetch manuf.descriptions manufd ");
    qs.append("left join fetch p.type type ");
    qs.append("left join fetch p.taxClass tx ");
    // RENTAL
    qs.append("left join fetch p.owner owner ");
    qs.append("where p.id=:pid and pa.region in (:lid) ");
    qs.append("and pd.language.id=:lang and papd.language.id=:lang ");
    qs.append("and p.available=true and p.dateAvailable<=:dt ");
    // this cannot be done on child elements from left join
    // qs.append("and pod.languageId=:lang and povd.languageId=:lang");
    String hql = qs.toString();
    Query q = this.em.createQuery(hql);
    q.setParameter("pid", productId);
    q.setParameter("lid", regionList);
    q.setParameter("dt", new Date());
    q.setParameter("lang", language.getId());
    @SuppressWarnings("unchecked") List<Product> results = q.getResultList();
    if (results.isEmpty())
        return null;
    else if (results.size() == 1)
        return results.get(0);
    throw new NonUniqueResultException();
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) Query(javax.persistence.Query) ArrayList(java.util.ArrayList) Product(com.salesmanager.core.model.catalog.product.Product) ProductList(com.salesmanager.core.model.catalog.product.ProductList) ArrayList(java.util.ArrayList) List(java.util.List) GenericEntityList(com.salesmanager.core.model.common.GenericEntityList) Date(java.util.Date)

Example 29 with NonUniqueResultException

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

the class NativePersistenceService method findIdByUniqueValues.

/**
 * Find a record uuid in table using its exact values
 *
 * @param sqlConnectionCode Code of the sql configuration
 * @param customTemplate Template related to the table
 * @param queryValues Values used to filter the result
 * @param fields
 * @return The uuid of the record if it was found or null if it was not
 */
public String findIdByUniqueValues(String sqlConnectionCode, CustomModelObject customTemplate, Map<String, Object> queryValues, Collection<CustomFieldTemplate> fields) {
    String result = null;
    String tableName = PostgresReserverdKeywords.escapeAndFormat(customTemplate.getDbTableName());
    if (queryValues.isEmpty()) {
        throw new IllegalArgumentException("Query values should not be empty");
    }
    StringBuilder q = new StringBuilder();
    q.append("SELECT uuid FROM {h-schema}" + tableName + " as a\n");
    Map<Integer, Object> queryParamers = new HashMap<>();
    Map<String, Object> uniqueValues = new HashMap<>();
    for (CustomFieldTemplate cft : fields) {
        if (cft.isUnique()) {
            Object uniqueValue = Optional.ofNullable(queryValues.get(cft.getCode())).orElse(queryValues.get(cft.getDbFieldname()));
            // Don't use inherited values
            if (uniqueValue != null && cft.getAppliesTo().equals(customTemplate.getAppliesTo())) {
                uniqueValues.put(cft.getDbFieldname(), uniqueValue);
            }
        }
    }
    if (uniqueValues.isEmpty()) {
        result = null;
    } else {
        AtomicInteger i = new AtomicInteger(1);
        uniqueValues.forEach((key, value) -> {
            key = PostgresReserverdKeywords.escapeAndFormat(key);
            if (!(value instanceof Collection) && !(value instanceof File) && !(value instanceof Map)) {
                if (value instanceof EntityReferenceWrapper) {
                    value = ((EntityReferenceWrapper) value).getUuid();
                }
                if (i.get() == 1) {
                    q.append("WHERE a." + key + " = ?\n");
                } else {
                    q.append("AND a." + key + " = ?\n");
                }
                queryParamers.put(i.getAndIncrement(), value);
            }
        });
        QueryBuilder builder = new QueryBuilder();
        builder.setSqlString(q.toString());
        Session session = crossStorageTransaction.getHibernateSession(sqlConnectionCode);
        NativeQuery<Map<String, Object>> query = builder.getNativeQuery(session, true);
        queryParamers.forEach((k, v) -> query.setParameter(k, v));
        try {
            Map<String, Object> singleResult = query.getSingleResult();
            result = (String) singleResult.get("uuid");
        } catch (NoResultException | NonUniqueResultException e) {
            result = null;
        } catch (Exception e) {
            log.error("Error executing query {}", query.getQueryString());
            throw e;
        }
    }
    if (result == null && customTemplate instanceof CustomEntityTemplate) {
        CustomEntityTemplate cet = (CustomEntityTemplate) customTemplate;
        CustomEntityTemplate superTemplate = cet.getSuperTemplate();
        if (superTemplate != null) {
            if (HibernateUtils.isLazyLoaded(superTemplate)) {
                superTemplate = customEntityTemplateService.findById(superTemplate.getId(), List.of("superTemplate"));
            }
            result = findIdByUniqueValues(sqlConnectionCode, superTemplate, queryValues, fields);
        }
    }
    return result;
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) HashMap(java.util.HashMap) QueryBuilder(org.meveo.commons.utils.QueryBuilder) NoResultException(javax.persistence.NoResultException) NoResultException(javax.persistence.NoResultException) NonUniqueResultException(javax.persistence.NonUniqueResultException) NotImplementedException(org.apache.commons.lang.NotImplementedException) ValidationException(org.meveo.admin.exception.ValidationException) BusinessException(org.meveo.admin.exception.BusinessException) PersistenceException(javax.persistence.PersistenceException) SQLException(java.sql.SQLException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EntityReferenceWrapper(org.meveo.model.crm.EntityReferenceWrapper) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) Collection(java.util.Collection) CustomModelObject(org.meveo.model.customEntities.CustomModelObject) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) Session(org.hibernate.Session)

Example 30 with NonUniqueResultException

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

the class GenericModuleService method loadModuleItem.

@SuppressWarnings("rawtypes")
public void loadModuleItem(MeveoModuleItem item) throws BusinessException {
    BusinessEntity entity = null;
    if (item.getItemClass().startsWith("org.meveo.model.technicalservice.endpoint.Endpoint")) {
        item.setItemClass("org.meveo.model.technicalservice.endpoint.Endpoint");
    }
    if (CustomFieldTemplate.class.getName().equals(item.getItemClass()) && item.getAppliesTo() != null) {
        entity = customFieldTemplateService.findByCodeAndAppliesToNoCache(item.getItemCode(), item.getAppliesTo());
        if (entity != null && entity.getCode() == null) {
            entity = null;
        }
    } else if (CustomEntityInstance.class.getName().equals(item.getItemClass()) && item.getAppliesTo() != null) {
        CustomEntityTemplate customEntityTemplate = customEntityTemplateService.findByCode(item.getAppliesTo());
        if (customEntityTemplate == null) {
            return;
        }
        Map<String, Object> ceiTable;
        try {
            ceiTable = crossStorageService.find(// XXX: Maybe we will need to parameterize this or search in all repositories ?
            repositoryService.findDefaultRepository(), customEntityTemplate, item.getItemCode(), // XXX: Maybe it should also be a parameter
            false);
        } catch (EntityDoesNotExistsException e) {
            ceiTable = null;
        }
        if (ceiTable != null) {
            CustomEntityInstance customEntityInstance = new CustomEntityInstance();
            customEntityInstance.setUuid((String) ceiTable.get("uuid"));
            customEntityInstance.setCode((String) ceiTable.get("uuid"));
            String fieldName = customFieldTemplateService.getFieldName(customEntityTemplate);
            if (fieldName != null) {
                Object description = null;
                Map<String, CustomFieldTemplate> customFieldTemplates = customFieldTemplateService.findByAppliesTo(customEntityTemplate.getAppliesTo());
                for (CustomFieldTemplate customFieldTemplate : customFieldTemplates.values()) {
                    if (customFieldTemplate != null && customFieldTemplate.getCode().toLowerCase().equals(fieldName)) {
                        description = ceiTable.get(customFieldTemplate.getCode());
                    }
                }
                customEntityInstance.setDescription(fieldName + ": " + description);
            }
            customEntityInstance.setCetCode(item.getAppliesTo());
            customEntityInstance.setCet(customEntityTemplate);
            customFieldInstanceService.setCfValues(customEntityInstance, item.getAppliesTo(), ceiTable);
            entity = customEntityInstance;
        }
    } else {
        String sql = "select mi from " + item.getItemClass() + " mi where mi.code=:code ";
        Class itemClazz;
        try {
            itemClazz = Class.forName(item.getItemClass());
        } catch (ClassNotFoundException e1) {
            log.error("Failed to find a module item {}. Module item class {} unknown", item, item.getItemClass());
            return;
        }
        boolean addFromParam = false;
        boolean addToParam = false;
        if (ReflectionUtils.isClassHasField(itemClazz, "validity")) {
            if (item.getValidity() != null && item.getValidity().getFrom() != null) {
                sql = sql + " and mi.validity.from = :from";
                addFromParam = true;
            } else {
                sql = sql + " and mi.validity.from IS NULL";
            }
            if (item.getValidity() != null && item.getValidity().getTo() != null) {
                sql = sql + " and mi.validity.to = :to";
                addToParam = true;
            } else {
                sql = sql + " and mi.validity.to IS NULL";
            }
        }
        final TypedQuery<BusinessEntity> query;
        try {
            query = getEntityManager().createQuery(sql, BusinessEntity.class);
        } catch (Exception e) {
            log.error("Can't build the following query : {}", sql, e);
            return;
        }
        query.setParameter("code", item.getItemCode());
        if (addFromParam) {
            query.setParameter("from", item.getValidity().getFrom());
        }
        if (addToParam) {
            query.setParameter("to", item.getValidity().getTo());
        }
        try {
            entity = query.getSingleResult();
        } catch (NoResultException e) {
            return;
        } catch (NonUniqueResultException e) {
            return;
        } catch (Exception e) {
            log.error("Failed to find a module item {}", item, e);
            return;
        }
    }
    // getEntityManager().detach(entity);
    item.setItemEntity(entity);
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) TypedQuery(javax.persistence.TypedQuery) NoResultException(javax.persistence.NoResultException) BusinessEntity(org.meveo.model.BusinessEntity) NoResultException(javax.persistence.NoResultException) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) NonUniqueResultException(javax.persistence.NonUniqueResultException) IOException(java.io.IOException) BusinessException(org.meveo.admin.exception.BusinessException) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) Map(java.util.Map) CustomEntityInstance(org.meveo.model.customEntities.CustomEntityInstance)

Aggregations

NonUniqueResultException (javax.persistence.NonUniqueResultException)64 NoResultException (javax.persistence.NoResultException)53 Query (javax.persistence.Query)29 EntityManager (javax.persistence.EntityManager)10 List (java.util.List)6 PersistenceException (javax.persistence.PersistenceException)6 Collection (java.util.Collection)5 QueryBuilder (org.meveo.commons.utils.QueryBuilder)5 IOException (java.io.IOException)4 Date (java.util.Date)4 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)4 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 ContextMappingInfo (org.jbpm.runtime.manager.impl.jpa.ContextMappingInfo)3 PopulationDataCriteria (de.symeda.sormas.api.infrastructure.PopulationDataCriteria)2