List of usage examples for org.hibernate Session getNamedQuery
org.hibernate.Query getNamedQuery(String queryName);
From source file:com.evolveum.midpoint.repo.sql.helpers.LookupTableHelper.java
License:Apache License
private void deleteRowById(Session session, String tableOid, Long id) { Query query = session.getNamedQuery("delete.lookupTableDataRow"); query.setString("oid", tableOid); query.setInteger("id", RUtil.toInteger(id)); query.executeUpdate();/*from w w w . j av a 2 s .c o m*/ }
From source file:com.evolveum.midpoint.repo.sql.helpers.LookupTableHelper.java
License:Apache License
private void deleteRowByKey(Session session, String tableOid, String key) { Query query = session.getNamedQuery("delete.lookupTableDataRowByKey"); query.setString("oid", tableOid); query.setString("key", key); query.executeUpdate();/*w w w .j a v a 2 s . c om*/ }
From source file:com.evolveum.midpoint.repo.sql.helpers.NameResolutionHelper.java
License:Apache License
public <C extends Containerable> void resolveNamesIfRequested(Session session, PrismContainerValue<C> containerValue, Collection<SelectorOptions<GetOperationOptions>> options) { GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); if (GetOperationOptions.isResolveNames(rootOptions)) { final List<String> oidsToResolve = new ArrayList<>(); Visitor oidExtractor = new Visitor() { @Override// ww w . j av a 2 s. c o m public void visit(Visitable visitable) { if (visitable instanceof PrismReferenceValue) { PrismReferenceValue value = (PrismReferenceValue) visitable; if (value.getTargetName() != null) { // just for sure return; } if (value.getObject() != null) { // improbable but possible value.setTargetName(value.getObject().getName()); return; } if (value.getOid() == null) { // shouldn't occur as well return; } oidsToResolve.add(value.getOid()); } } }; containerValue.accept(oidExtractor); if (!oidsToResolve.isEmpty()) { Query query = session.getNamedQuery("resolveReferences"); query.setParameterList("oid", oidsToResolve); query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); List<Map<String, Object>> results = query.list(); final Map<String, PolyString> oidNameMap = consolidateResults(results); Visitor nameSetter = new Visitor() { @Override public void visit(Visitable visitable) { if (visitable instanceof PrismReferenceValue) { PrismReferenceValue value = (PrismReferenceValue) visitable; if (value.getTargetName() == null && value.getOid() != null) { value.setTargetName(oidNameMap.get(value.getOid())); } } } }; containerValue.accept(nameSetter); } } }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
License:Apache License
public <T extends ObjectType> PrismObject<T> getObjectInternal(Session session, Class<T> type, String oid, Collection<SelectorOptions<GetOperationOptions>> options, boolean lockForUpdate, OperationResult operationResult) throws ObjectNotFoundException, SchemaException, DtoTranslationException { boolean lockedForUpdateViaHibernate = false; boolean lockedForUpdateViaSql = false; LockOptions lockOptions = new LockOptions(); //todo fix lock for update!!!!! if (lockForUpdate) { if (getConfiguration().isLockForUpdateViaHibernate()) { lockOptions.setLockMode(LockMode.PESSIMISTIC_WRITE); lockedForUpdateViaHibernate = true; } else if (getConfiguration().isLockForUpdateViaSql()) { LOGGER.trace("Trying to lock object {} for update (via SQL)", oid); long time = System.currentTimeMillis(); SQLQuery q = session.createSQLQuery("select oid from m_object where oid = ? for update"); q.setString(0, oid);/*from w w w.jav a2s . c o m*/ Object result = q.uniqueResult(); if (result == null) { return throwObjectNotFoundException(type, oid); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Locked via SQL (in {} ms)", System.currentTimeMillis() - time); } lockedForUpdateViaSql = true; } } if (LOGGER.isTraceEnabled()) { if (lockedForUpdateViaHibernate) { LOGGER.trace("Getting object {} with locking for update (via hibernate)", oid); } else if (lockedForUpdateViaSql) { LOGGER.trace("Getting object {}, already locked for update (via SQL)", oid); } else { LOGGER.trace("Getting object {} without locking for update", oid); } } GetObjectResult fullObject = null; if (!lockForUpdate) { Query query = session.getNamedQuery("get.object"); query.setString("oid", oid); query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER); query.setLockOptions(lockOptions); fullObject = (GetObjectResult) query.uniqueResult(); } else { // we're doing update after this get, therefore we load full object right now // (it would be loaded during merge anyway) // this just loads object to hibernate session, probably will be removed later. Merge after this get // will be faster. Read and use object only from fullObject column. // todo remove this later [lazyman] Criteria criteria = session.createCriteria(ClassMapper.getHQLTypeClass(type)); criteria.add(Restrictions.eq("oid", oid)); criteria.setLockMode(lockOptions.getLockMode()); RObject obj = (RObject) criteria.uniqueResult(); if (obj != null) { obj.toJAXB(prismContext, null).asPrismObject(); fullObject = new GetObjectResult(obj.getFullObject(), obj.getStringsCount(), obj.getLongsCount(), obj.getDatesCount(), obj.getReferencesCount(), obj.getPolysCount(), obj.getBooleansCount()); } } LOGGER.trace("Got it."); if (fullObject == null) { throwObjectNotFoundException(type, oid); } LOGGER.trace("Transforming data to JAXB type."); PrismObject<T> prismObject = updateLoadedObject(fullObject, type, oid, options, session, operationResult); validateObjectType(prismObject, type); // this was implemented to allow report parsing errors as warnings to upper layers; // however, it causes problems when serialization problems are encountered: in such cases, we put // FATAL_ERROR to the result here, and it should be then removed or muted (which is a complication) // -- so, as the parsing errors are not implemented, we disabled this code as well // subResult.computeStatusIfUnknown(); // if (subResult.isWarning() || subResult.isError() || subResult.isInProgress()) { // prismObject.asObjectable().setFetchResult(subResult.createOperationResultType()); // } return prismObject; }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
License:Apache License
public <F extends FocusType> PrismObject<F> searchShadowOwnerAttempt(String shadowOid, Collection<SelectorOptions<GetOperationOptions>> options, OperationResult result) { LOGGER_PERFORMANCE.debug("> search shadow owner for oid={}", shadowOid); PrismObject<F> owner = null;/* w w w . j a v a2s.c o m*/ Session session = null; try { session = baseHelper.beginReadOnlyTransaction(); LOGGER.trace("Selecting account shadow owner for account {}.", new Object[] { shadowOid }); Query query = session.getNamedQuery("searchShadowOwner.getOwner"); query.setString("oid", shadowOid); query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER); List<GetObjectResult> focuses = query.list(); LOGGER.trace("Found {} focuses, transforming data to JAXB types.", new Object[] { (focuses != null ? focuses.size() : 0) }); if (focuses == null || focuses.isEmpty()) { // account shadow owner was not found return null; } if (focuses.size() > 1) { LOGGER.warn("Found {} owners for shadow oid {}, returning first owner.", new Object[] { focuses.size(), shadowOid }); } GetObjectResult focus = focuses.get(0); owner = updateLoadedObject(focus, (Class<F>) FocusType.class, null, options, session, result); session.getTransaction().commit(); } catch (SchemaException | RuntimeException ex) { baseHelper.handleGeneralException(ex, session, result); } finally { baseHelper.cleanupSessionAndResult(session, result); } return owner; }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
License:Apache License
public PrismObject<UserType> listAccountShadowOwnerAttempt(String accountOid, OperationResult result) throws ObjectNotFoundException { LOGGER_PERFORMANCE.debug("> list account shadow owner oid={}", accountOid); PrismObject<UserType> userType = null; Session session = null; try {/* ww w . j av a2 s . co m*/ session = baseHelper.beginReadOnlyTransaction(); Query query = session.getNamedQuery("listAccountShadowOwner.getUser"); query.setString("oid", accountOid); query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER); List<GetObjectResult> users = query.list(); LOGGER.trace("Found {} users, transforming data to JAXB types.", new Object[] { (users != null ? users.size() : 0) }); if (users == null || users.isEmpty()) { // account shadow owner was not found return null; } if (users.size() > 1) { LOGGER.warn("Found {} users for account oid {}, returning first user. [interface change needed]", new Object[] { users.size(), accountOid }); } GetObjectResult user = users.get(0); userType = updateLoadedObject(user, UserType.class, null, null, session, result); session.getTransaction().commit(); } catch (SchemaException | RuntimeException ex) { baseHelper.handleGeneralException(ex, session, result); } finally { baseHelper.cleanupSessionAndResult(session, result); } return userType; }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
License:Apache License
/** * This method provides object parsing from String and validation. *//*from w ww . j ava 2s. c o m*/ private <T extends ObjectType> PrismObject<T> updateLoadedObject(GetObjectResult result, Class<T> type, String oid, Collection<SelectorOptions<GetOperationOptions>> options, Session session, OperationResult operationResult) throws SchemaException { String xml = RUtil.getXmlFromByteArray(result.getFullObject(), getConfiguration().isUseZip()); PrismObject<T> prismObject; try { // "Postel mode": be tolerant what you read. We need this to tolerate (custom) schema changes ParsingContext parsingContext = ParsingContext.forMode(XNodeProcessorEvaluationMode.COMPAT); prismObject = prismContext.parseObject(xml, parsingContext); // TODO enable if needed // if (parsingContext.hasWarnings()) { // for (String warning : parsingContext.getWarnings()) { // operationResult.createSubresult("parseObject").recordWarning(warning); // } // } } catch (SchemaException | RuntimeException | Error e) { // This is a serious thing. We have corrupted XML in the repo. This may happen even // during system init. We want really loud and detailed error here. LOGGER.error("Couldn't parse object {} {}: {}: {}\n{}", type.getSimpleName(), oid, e.getClass().getName(), e.getMessage(), xml, e); throw e; } if (FocusType.class.isAssignableFrom(prismObject.getCompileTimeClass())) { if (SelectorOptions.hasToLoadPath(FocusType.F_JPEG_PHOTO, options)) { //todo improve, use user.hasPhoto flag and take options into account [lazyman] //this is called only when options contains INCLUDE user/jpegPhoto Query query = session.getNamedQuery("get.focusPhoto"); query.setString("oid", prismObject.getOid()); byte[] photo = (byte[]) query.uniqueResult(); if (photo != null) { PrismProperty property = prismObject.findOrCreateProperty(FocusType.F_JPEG_PHOTO); property.setRealValue(photo); } } } else if (ShadowType.class.equals(prismObject.getCompileTimeClass())) { //we store it because provisioning now sends it to repo, but it should be transient prismObject.removeContainer(ShadowType.F_ASSOCIATION); LOGGER.debug("Loading definitions for shadow attributes."); Short[] counts = result.getCountProjection(); Class[] classes = GetObjectResult.EXT_COUNT_CLASSES; for (int i = 0; i < classes.length; i++) { if (counts[i] == null || counts[i] == 0) { continue; } applyShadowAttributeDefinitions(classes[i], prismObject, session); } LOGGER.debug("Definitions for attributes loaded. Counts: {}", Arrays.toString(counts)); } else if (LookupTableType.class.equals(prismObject.getCompileTimeClass())) { lookupTableHelper.updateLoadedLookupTable(prismObject, options, session); } else if (AccessCertificationCampaignType.class.equals(prismObject.getCompileTimeClass())) { caseHelper.updateLoadedCampaign(prismObject, options, session); } nameResolutionHelper.resolveNamesIfRequested(session, prismObject.getValue(), options); validateObjectType(prismObject, type); return prismObject; }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
License:Apache License
private void applyShadowAttributeDefinitions(Class<? extends RAnyValue> anyValueType, PrismObject object, Session session) throws SchemaException { PrismContainer attributes = object.findContainer(ShadowType.F_ATTRIBUTES); Query query = session.getNamedQuery("getDefinition." + anyValueType.getSimpleName()); query.setParameter("oid", object.getOid()); query.setParameter("ownerType", RObjectExtensionType.ATTRIBUTES); List<Object[]> values = query.list(); if (values == null || values.isEmpty()) { return;/*from w w w . java 2 s. com*/ } for (Object[] value : values) { QName name = RUtil.stringToQName((String) value[0]); QName type = RUtil.stringToQName((String) value[1]); Item item = attributes.findItem(name); // A switch statement used to be here // but that caused strange trouble with OpenJDK. This if-then-else works. if (item.getDefinition() == null) { RValueType rValType = (RValueType) value[2]; if (rValType == RValueType.PROPERTY) { PrismPropertyDefinition<Object> def = new PrismPropertyDefinition<Object>(name, type, object.getPrismContext()); item.applyDefinition(def, true); } else if (rValType == RValueType.REFERENCE) { PrismReferenceDefinition def = new PrismReferenceDefinition(name, type, object.getPrismContext()); item.applyDefinition(def, true); } else { throw new UnsupportedOperationException("Unsupported value type " + rValType); } } } }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
License:Apache License
public <T extends ShadowType> List<PrismObject<T>> listResourceObjectShadowsAttempt(String resourceOid, Class<T> resourceObjectShadowType, OperationResult result) throws ObjectNotFoundException, SchemaException { LOGGER_PERFORMANCE.debug("> list resource object shadows {}, for resource oid={}", new Object[] { resourceObjectShadowType.getSimpleName(), resourceOid }); List<PrismObject<T>> list = new ArrayList<>(); Session session = null; try {/*from w w w .java2 s.c o m*/ session = baseHelper.beginReadOnlyTransaction(); Query query = session.getNamedQuery("listResourceObjectShadows"); query.setString("oid", resourceOid); query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER); List<GetObjectResult> shadows = query.list(); LOGGER.debug("Query returned {} shadows, transforming to JAXB types.", new Object[] { (shadows != null ? shadows.size() : 0) }); if (shadows != null) { for (GetObjectResult shadow : shadows) { PrismObject<T> prismObject = updateLoadedObject(shadow, resourceObjectShadowType, null, null, session, result); list.add(prismObject); } } session.getTransaction().commit(); } catch (SchemaException | RuntimeException ex) { baseHelper.handleGeneralException(ex, session, result); } finally { baseHelper.cleanupSessionAndResult(session, result); } return list; }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
License:Apache License
public <T extends ObjectType> String getVersionAttempt(Class<T> type, String oid, OperationResult result) throws ObjectNotFoundException, SchemaException { LOGGER_PERFORMANCE.debug("> get version {}, oid={}", new Object[] { type.getSimpleName(), oid }); String version = null;/*from ww w.j ava2 s . c o m*/ Session session = null; try { session = baseHelper.beginReadOnlyTransaction(); Query query = session.getNamedQuery("getVersion"); query.setString("oid", oid); Number versionLong = (Number) query.uniqueResult(); if (versionLong == null) { throw new ObjectNotFoundException( "Object '" + type.getSimpleName() + "' with oid '" + oid + "' was not found."); } version = versionLong.toString(); session.getTransaction().commit(); } catch (RuntimeException ex) { baseHelper.handleGeneralRuntimeException(ex, session, result); } finally { baseHelper.cleanupSessionAndResult(session, result); } return version; }