Example usage for org.hibernate Query setString

List of usage examples for org.hibernate Query setString

Introduction

In this page you can find the example usage for org.hibernate Query setString.

Prototype

@Deprecated
@SuppressWarnings("unchecked")
default Query<R> setString(String name, String val) 

Source Link

Document

Bind a named String-valued parameter.

Usage

From source file:com.evolveum.midpoint.repo.sql.helpers.OrgClosureManager.java

License:Apache License

private List<String> getChildren(String oid, Session session) {
    Query childrenQuery = session
            .createQuery("select distinct parentRef.ownerOid from RObjectReference as parentRef"
                    + " join parentRef.owner as owner where parentRef.targetOid=:oid and parentRef.referenceType=0"
                    + " and owner.objectTypeClass = :orgType");
    childrenQuery.setParameter("orgType", RObjectType.ORG); // TODO eliminate use of parameter here
    childrenQuery.setString("oid", oid);
    return childrenQuery.list();
}

From source file:com.evolveum.midpoint.repo.sql.OrgClosureManager.java

License:Apache License

/**
 * 1->2// w  w  w. j  a  v a2 s.c o  m
 * 1->3
 * 2->4
 * 3->4
 * 3->5
 * <p/>
 * a d
 * 1 1 0
 * 1 2 1
 * 1 3 1  -
 * 1 4 2
 * 1 5 2  *****
 * 2 2 0
 * 2 4 1
 * 3 3 0  -
 * 3 4 1  -
 * 3 5 1  -
 * 4 4 0
 * 5 5 0
 * <p/>
 * deleting 3
 * <p/>
 * 1->2
 * 2->4
 * 5
 * <p/>
 * a d
 * 1 1 0
 * 1 2 1
 * 1 4 2
 * 2 2 0
 * 2 4 1
 * 4 4 0
 * 5 5 0
 * <p/>
 * <p/>
 * remove all with ancestor = 3
 * remove all with descendant = 3
 * <p/>
 * deleting 5
 * remove all with ancestor = 5
 * remove all with descendant = 5
 * <p/>
 * deleting ref 1->3 (parentRef = 1 in object 3)
 * update depth all children of 3 and new depth = depth - (1->3 depth which is 1 based on 1 3 1)
 * remove 1 3 1
 */
private <T extends ObjectType> void handleDelete(Collection<? extends ItemDelta> modifications, Session session,
        String oid, Class<T> type) {

    //        "select distinct o.descendantOid from ROrgClosure as o where o.ancestorId=0 and o.ancestorOid=:oid";
    //        "select distinct o.ancestorOid from ROrgClosure as o " +
    //                "where o.descendantId=0 and o.descendantOid=:oid and and o.ancestorId=0 o.ancestorOid != :oid";

    LOGGER.trace("Deleting org. closure for object {} {}", oid, type.getSimpleName());
    Query query = session.createQuery(
            "select distinct o.ancestorOid from ROrgClosure as o where o.descendantId=0 and o.descendantOid=:dOid");

    query = session.createQuery("delete from ROrgClosure as o where (o.ancestorId=0 and "
            + "o.ancestorOid=:aOid) or (o.descendantId=0 and o.descendantOid=:dOid)");
    query.setString("aOid", oid);
    query.setString("dOid", oid);
    int count = query.executeUpdate();
    LOGGER.trace("Deleted {} records.", count);
}

From source file:com.evolveum.midpoint.repo.sql.query.custom.OrgFilterQuery.java

License:Apache License

@Override
public RQuery createQuery(ObjectQuery objectQuery, Class<? extends ObjectType> type,
        Collection<SelectorOptions<GetOperationOptions>> options, boolean countingObjects, Session session) {

    OrgFilter filter = (OrgFilter) objectQuery.getFilter();

    LOGGER.trace("createOrgQuery {}, counting={}, filter={}",
            new Object[] { type.getSimpleName(), countingObjects, filter });

    if (countingObjects) {
        return countQuery(filter, type, session);
    }//from   ww w.j av  a 2  s.co  m

    StringBuilder sb = new StringBuilder();
    if (OrgFilter.Scope.ONE_LEVEL.equals(filter.getScope())) {
        sb.append(
                "select o.fullObject,o.stringsCount,o.longsCount,o.datesCount,o.referencesCount,o.polysCount,o.booleansCount from ");
        sb.append(ClassMapper.getHQLType(type)).append(
                " as o where o.oid in (select distinct p.ownerOid from RObjectReference p where p.targetOid=:oid and p.referenceType=0)");
    } else {
        sb.append(
                "select o.fullObject,o.stringsCount,o.longsCount,o.datesCount,o.referencesCount,o.polysCount,o.booleansCount from ");
        sb.append(ClassMapper.getHQLType(type)).append(" as o where o.oid in (");
        //todo change to sb.append("select d.descendantOid from ROrgClosure as d where d.ancestorOid = :oid and d.descendantOid != :oid)");
        sb.append(
                "select distinct d.descendantOid from ROrgClosure as d where d.ancestorOid = :oid and d.descendantOid != :oid)");
    }
    Query query = session.createQuery(sb.toString());
    query.setString("oid", filter.getOrgRef().getOid());
    query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);

    return new RQueryImpl(query);
}

From source file:com.evolveum.midpoint.repo.sql.query.custom.OrgFilterQuery.java

License:Apache License

private RQuery countQuery(OrgFilter filter, Class type, Session session) {
    StringBuilder sb = new StringBuilder();
    if (OrgFilter.Scope.ONE_LEVEL.equals(filter.getScope())) {
        sb.append("select count(distinct o.oid) from ");
        sb.append(ClassMapper.getHQLType(type)).append(" o left join o.parentOrgRef p where p.targetOid=:oid");
    } else {/*from   w  ww .  j  a  va 2  s.c  om*/
        if (ObjectType.class.equals(type)) {
            //todo change to select count(*) from ROrgClosure d where d.ancestorOid = :oid
            sb.append(
                    "select count(distinct d.descendantOid) from ROrgClosure d where d.ancestorOid = :oid and d.descendantOid != :oid");
        } else {
            //todo change to sb.append("select count(d.descendantOid) from ").append(ClassMapper.getHQLType(type));
            sb.append("select count(distinct d.descendantOid) from ").append(ClassMapper.getHQLType(type));
            sb.append(
                    " as o left join o.descendants as d where d.ancestorOid = :oid and d.descendantOid != :oid");
        }
    }
    Query query = session.createQuery(sb.toString());
    query.setString("oid", filter.getOrgRef().getOid());

    return new RQueryImpl(query);
}

From source file:com.evolveum.midpoint.repo.sql.query.OrgFilterQuery.java

License:Apache License

@Override
public RQuery createQuery(ObjectQuery objectQuery, Class<? extends ObjectType> type,
        Collection<SelectorOptions<GetOperationOptions>> options, boolean countingObjects, Session session) {

    OrgFilter filter = (OrgFilter) objectQuery.getFilter();

    LOGGER.trace("createOrgQuery {}, counting={}, filter={}",
            new Object[] { type.getSimpleName(), countingObjects, filter });

    if (countingObjects) {
        return countQuery(filter, type, session);
    }/*from   w  w w . j  a v  a2 s.c o m*/

    StringBuilder sb = new StringBuilder();
    if (OrgFilter.Scope.ONE_LEVEL.equals(filter.getScope())) {
        sb.append(
                "select o.fullObject,o.stringsCount,o.longsCount,o.datesCount,o.referencesCount,o.polysCount from ");
        sb.append(ClassMapper.getHQLType(type)).append(
                " as o where o.oid in (select distinct p.ownerOid from RParentOrgRef p where p.targetOid=:oid)");
    } else {
        sb.append(
                "select o.fullObject,o.stringsCount,o.longsCount,o.datesCount,o.referencesCount,o.polysCount from ");
        sb.append(ClassMapper.getHQLType(type)).append(" as o where o.oid in (");
        //todo change to sb.append("select d.descendantOid from ROrgClosure as d where d.ancestorOid = :oid and d.descendantOid != :oid)");
        sb.append(
                "select distinct d.descendantOid from ROrgClosure as d where d.ancestorOid = :oid and d.descendantOid != :oid)");
    }
    Query query = session.createQuery(sb.toString());
    query.setString("oid", filter.getOrgRef().getOid());
    query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);

    return new RQueryImpl(query);
}

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  . j ava2 s. 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;//from  ww w . j  a va  2s.c  o m
    try {
        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 <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  w  w . j  av  a  2 s . 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

private <T extends ObjectType> List<ReferenceDelta> createDeleteParentRefDelta(Class<T> type, String oid,
        Session session) {//from www .j a  v  a  2s.co  m
    Query query = session.createQuery("from RParentOrgRef as r where r.ownerOid = :oid");
    query.setString("oid", oid);

    List<RObjectReference> references = query.list();
    if (references == null || references.isEmpty()) {
        return new ArrayList<>();
    }

    List<PrismReferenceValue> values = new ArrayList<>();
    for (RObjectReference ref : references) {
        ObjectReferenceType refType = new ObjectReferenceType();
        RObjectReference.copyToJAXB(ref, refType, getPrismContext());

        values.add(refType.asReferenceValue());
    }

    PrismObjectDefinition def = getPrismContext().getSchemaRegistry()
            .findObjectDefinitionByCompileTimeClass(type);
    ReferenceDelta delta = ReferenceDelta.createModificationDelete(new ItemPath(ObjectType.F_PARENT_ORG_REF),
            def, values);

    return Arrays.asList(delta);
}