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();
}
}
}
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;
}
}
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();
}
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;
}
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);
}
Aggregations