List of usage examples for org.hibernate Session getNamedQuery
org.hibernate.Query getNamedQuery(String queryName);
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
License:Apache License
public boolean isAnySubordinateAttempt(String upperOrgOid, Collection<String> lowerObjectOids) { Session session = null; try {/*from w ww. ja v a2 s .c om*/ session = baseHelper.beginReadOnlyTransaction(); Query query; if (lowerObjectOids.size() == 1) { query = session.getNamedQuery("isAnySubordinateAttempt.oneLowerOid"); query.setString("dOid", lowerObjectOids.iterator().next()); } else { query = session.getNamedQuery("isAnySubordinateAttempt.moreLowerOids"); query.setParameterList("dOids", lowerObjectOids); } query.setString("aOid", upperOrgOid); Number number = (Number) query.uniqueResult(); session.getTransaction().commit(); return number != null && number.longValue() != 0L; } catch (RuntimeException ex) { baseHelper.handleGeneralException(ex, session, null); } finally { baseHelper.cleanupSessionAndResult(session, null); } throw new SystemException("isAnySubordinateAttempt failed somehow, this really should not happen."); }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
private <T extends ObjectType> PrismObject<T> getObject(Session session, Class<T> type, String oid, Collection<SelectorOptions<GetOperationOptions>> options, boolean lockForUpdate) throws ObjectNotFoundException, SchemaException, DtoTranslationException, QueryException { 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()) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Trying to lock object " + oid + " for update (via SQL)"); }/*from w w w. jav a2s . co m*/ long time = System.currentTimeMillis(); SQLQuery q = session.createSQLQuery("select oid from m_object where oid = ? for update"); q.setString(0, oid); Object result = q.uniqueResult(); if (result == null) { return throwObjectNotFoundException(type, oid); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Locked via SQL (in " + (System.currentTimeMillis() - time) + " ms)"); } lockedForUpdateViaSql = true; } } if (LOGGER.isTraceEnabled()) { if (lockedForUpdateViaHibernate) { LOGGER.trace("Getting object " + oid + " with locking for update (via hibernate)"); } else if (lockedForUpdateViaSql) { LOGGER.trace("Getting object " + oid + ", already locked for update (via SQL)"); } else { LOGGER.trace("Getting object " + oid + " without locking for update"); } } 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(getPrismContext(), null).asPrismObject(); fullObject = new GetObjectResult(obj.getFullObject(), obj.getStringsCount(), obj.getLongsCount(), obj.getDatesCount(), obj.getReferencesCount(), obj.getPolysCount()); } } LOGGER.trace("Got it."); if (fullObject == null) { throwObjectNotFoundException(type, oid); } LOGGER.trace("Transforming data to JAXB type."); PrismObject<T> prismObject = updateLoadedObject(fullObject, type, options, session); validateObjectType(prismObject, type); return prismObject; }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
private <F extends FocusType> PrismObject<F> searchShadowOwnerAttempt(String shadowOid, OperationResult result) throws ObjectNotFoundException { PrismObject<F> owner = null;//from w w w . j av a 2 s. c o m Session session = null; try { session = beginReadOnlyTransaction(); Query query = session.getNamedQuery("searchShadowOwner.getShadow"); query.setString("oid", shadowOid); if (query.uniqueResult() == null) { throw new ObjectNotFoundException("Shadow with oid '" + shadowOid + "' doesn't exist."); } LOGGER.trace("Selecting account shadow owner for account {}.", new Object[] { shadowOid }); 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, session); session.getTransaction().commit(); } catch (ObjectNotFoundException ex) { rollbackTransaction(session, ex, result, true); throw ex; } catch (SchemaException | RuntimeException ex) { handleGeneralException(ex, session, result); } finally { cleanupSessionAndResult(session, result); } return owner; }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
private PrismObject<UserType> listAccountShadowOwnerAttempt(String accountOid, OperationResult result) throws ObjectNotFoundException { PrismObject<UserType> userType = null; Session session = null; try {/*from w w w.java 2s . c om*/ session = 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, session); session.getTransaction().commit(); } catch (SchemaException | RuntimeException ex) { handleGeneralException(ex, session, result); } finally { cleanupSessionAndResult(session, result); } return userType; }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
private boolean existOrgCLosure(Session session, String ancestorOid, String descendantOid, int depth) { // if not exist pair with same depth, then create else nothing do Query qExistClosure = session.getNamedQuery("existOrgClosure"); qExistClosure.setParameter("ancestorOid", ancestorOid); qExistClosure.setParameter("descendantOid", descendantOid); qExistClosure.setParameter("depth", depth); return (Long) qExistClosure.uniqueResult() != 0; }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
private boolean existIncorrect(Session session, String ancestorOid, String descendantOid) { // if not exist pair with same depth, then create else nothing do Query qExistIncorrect = session.getNamedQuery("existIncorrect"); qExistIncorrect.setParameter("ancestorOid", ancestorOid); qExistIncorrect.setParameter("descendantOid", descendantOid); return (Long) qExistIncorrect.uniqueResult() != 0; }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
private <T extends ObjectType> void fillHierarchy(RObject<T> rOrg, Session session, boolean withIncorrect) throws SchemaException { if (!existOrgCLosure(session, rOrg.getOid(), rOrg.getOid(), 0)) { ROrgClosure closure = new ROrgClosure(rOrg, rOrg, 0); session.save(closure);/*from w ww . j a va 2s.c o m*/ } for (RObjectReference orgRef : rOrg.getParentOrgRef()) { fillTransitiveHierarchy(rOrg, orgRef.getTargetOid(), session, withIncorrect); } if (withIncorrect) { Query qIncorrect = session.getNamedQuery("fillHierarchy"); qIncorrect.setString("oid", rOrg.getOid()); List<ROrgIncorrect> orgIncorrect = qIncorrect.list(); for (ROrgIncorrect orgInc : orgIncorrect) { Query qObject = session.createQuery("from RObject where oid = :oid"); qObject.setString("oid", orgInc.getDescendantOid()); RObject rObjectI = (RObject) qObject.uniqueResult(); if (rObjectI != null) { fillTransitiveHierarchy(rObjectI, rOrg.getOid(), session, !withIncorrect); session.delete(orgInc); } } } }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
/** * This method provides object parsing from String and validation. *//* www. ja v a2s. c o m*/ private <T extends ObjectType> PrismObject<T> updateLoadedObject(GetObjectResult result, Class<T> type, Collection<SelectorOptions<GetOperationOptions>> options, Session session) throws SchemaException { String xml = RUtil.getXmlFromByteArray(result.getFullObject(), getConfiguration().isUseZip()); PrismObject<T> prismObject; try { prismObject = getPrismContext().parseObject(xml); } catch (SchemaException e) { LOGGER.debug("Couldn't parse object because of schema exception ({}):\nObject: {}", e, xml); throw e; } if (UserType.class.equals(prismObject.getCompileTimeClass())) { if (SelectorOptions.hasToLoadPath(UserType.F_JPEG_PHOTO, options)) { //todo improve, use user.hasPhoto flag and take options into account [lazyman] //call this only when options contains INCLUDE user/jpegPhoto Query query = session.getNamedQuery("get.userPhoto"); query.setString("oid", prismObject.getOid()); byte[] photo = (byte[]) query.uniqueResult(); if (photo != null) { PrismProperty property = prismObject.findOrCreateProperty(UserType.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)); } validateObjectType(prismObject, type); return prismObject; }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.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;//w w w.j a v a2 s.com } for (Object[] value : values) { ItemDefinition def; QName name = RUtil.stringToQName((String) value[0]); QName type = RUtil.stringToQName((String) value[1]); switch ((RValueType) value[2]) { case PROPERTY: def = new PrismPropertyDefinition(name, type, object.getPrismContext()); break; case REFERENCE: def = new PrismReferenceDefinition(name, type, object.getPrismContext()); break; default: throw new UnsupportedOperationException("Unsupported value type " + value[2]); } Item item = attributes.findItem(def.getName()); if (item.getDefinition() == null) { item.applyDefinition(def, true); } } }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
private void deleteHierarchy(RObject objectToDelete, Session session) { session.getNamedQuery("sqlDeleteOrgClosure").setParameter("oid", objectToDelete.getOid()).executeUpdate(); session.getNamedQuery("sqlDeleteOrgIncorrect").setParameter("oid", objectToDelete.getOid()).executeUpdate(); }