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.closure.AbstractOrgClosureTest.java

License:Apache License

private List<ROrgClosure> getOrgClosureByDescendant(String descendantOid) {
    Query query = getSession().createQuery("from ROrgClosure where descendantOid=:oid");
    query.setString("oid", descendantOid);
    return query.list();
}

From source file:com.evolveum.midpoint.repo.sql.closure.AbstractOrgClosureTest.java

License:Apache License

private List<ROrgClosure> getOrgClosureByAncestor(String ancestorOid) {
    Query query = getSession().createQuery("from ROrgClosure where ancestorOid=:oid");
    query.setString("oid", ancestorOid);
    return query.list();
}

From source file:com.evolveum.midpoint.repo.sql.closure.AbstractOrgClosureTest.java

License:Apache License

protected List<String> getChildren(String oid) {
    Query childrenQuery = getSession().createQuery(
            "select distinct ownerOid from RObjectReference where targetOid=:oid and referenceType=0");
    childrenQuery.setString("oid", oid);
    return childrenQuery.list();
}

From source file:com.evolveum.midpoint.repo.sql.closure.AbstractOrgClosureTest.java

License:Apache License

private List<String> getOrgChildren(String oid) {
    Query childrenQuery = getSession()
            .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.helpers.CertificationCaseHelper.java

License:Apache License

protected List<Long> addOrDeleteCases(Session session, String campaignOid,
        Collection<? extends ItemDelta> modifications) throws SchemaException, DtoTranslationException {
    final ItemPath casePath = new ItemPath(AccessCertificationCampaignType.F_CASE);
    boolean replacePresent = false;
    List<Long> affectedIds = new ArrayList<>();
    for (ItemDelta delta : modifications) {
        ItemPath deltaPath = delta.getPath();
        if (!casePath.isSubPathOrEquivalent(deltaPath)) {
            throw new IllegalStateException("Wrong campaign delta sneaked into updateCampaignCases: class="
                    + delta.getClass() + ", path=" + deltaPath);
        }/*from   w  w w. j a  v  a 2  s .  c  o  m*/

        if (deltaPath.size() == 1) {
            if (delta.getValuesToDelete() != null) {
                // todo do 'bulk' delete like delete from ... where oid=? and id in (...)
                for (PrismContainerValue value : (Collection<PrismContainerValue>) delta.getValuesToDelete()) {
                    Long id = value.getId();
                    if (id == null) {
                        throw new SchemaException("Couldn't delete certification case with null id");
                    }
                    affectedIds.add(id);
                    // TODO couldn't this cascading be done by hibernate itself?
                    Integer integerCaseId = RUtil.toInteger(id);
                    Query deleteCaseDecisions = session.getNamedQuery("delete.campaignCaseDecisions");
                    deleteCaseDecisions.setString("oid", campaignOid);
                    deleteCaseDecisions.setInteger("id", integerCaseId);
                    deleteCaseDecisions.executeUpdate();
                    Query deleteCaseReferences = session.createSQLQuery("delete from "
                            + RCertCaseReference.TABLE + " where owner_owner_oid=:oid and owner_id=:id");
                    deleteCaseReferences.setString("oid", campaignOid);
                    deleteCaseReferences.setInteger("id", integerCaseId);
                    deleteCaseReferences.executeUpdate();
                    Query deleteCase = session.getNamedQuery("delete.campaignCase");
                    deleteCase.setString("oid", campaignOid);
                    deleteCase.setInteger("id", integerCaseId);
                    deleteCase.executeUpdate();
                }
            }
            // TODO generated IDs might conflict with client-provided ones
            // also, client-provided IDs might conflict with those that are already in the database
            // So it's safest not to provide any IDs by the client
            if (delta.getValuesToAdd() != null) {
                int currentId = generalHelper.findLastIdInRepo(session, campaignOid, "get.campaignCaseLastId")
                        + 1;
                addCertificationCampaignCases(session, campaignOid, delta.getValuesToAdd(), currentId,
                        affectedIds);
            }
            if (delta.getValuesToReplace() != null) {
                deleteCertificationCampaignCases(session, campaignOid);
                addCertificationCampaignCases(session, campaignOid, delta.getValuesToReplace(), 1, affectedIds);
                replacePresent = true;
            }

        }
    }
    return replacePresent ? null : affectedIds;
}

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

License:Apache License

private void updateCasesContent(Session session, String campaignOid,
        Collection<? extends ItemDelta> modifications, List<Long> casesAddedOrDeleted,
        RepoModifyOptions modifyOptions)
        throws SchemaException, ObjectNotFoundException, DtoTranslationException {
    Set<Long> casesModified = new HashSet<>();
    for (ItemDelta delta : modifications) {
        ItemPath deltaPath = delta.getPath();
        if (deltaPath.size() > 1) {
            LOGGER.trace("Updating campaign " + campaignOid + " with delta " + delta);

            // should start with "case[id]"
            long id = checkPathSanity(deltaPath, casesAddedOrDeleted);

            Query query = session.getNamedQuery("get.campaignCase");
            query.setString("ownerOid", campaignOid);
            query.setInteger("id", (int) id);

            byte[] fullObject = (byte[]) query.uniqueResult();
            if (fullObject == null) {
                throw new ObjectNotFoundException("Couldn't update cert campaign " + campaignOid
                        + " + by delta with path " + deltaPath + " - specified case does not exist");
            }//from w  w w  . j  a  v a2s . com
            AccessCertificationCaseType aCase = RAccessCertificationCase.createJaxb(fullObject, prismContext,
                    false);

            delta = delta.clone(); // to avoid changing original modifications
            delta.setParentPath(delta.getParentPath().tail(2)); // remove "case[id]" from the delta path
            delta.applyTo(aCase.asPrismContainerValue());

            // we need to generate IDs but we (currently) do not use that for setting "isTransient" flag
            PrismIdentifierGenerator generator = new PrismIdentifierGenerator();
            generator.generate(aCase, PrismIdentifierGenerator.Operation.MODIFY);

            RAccessCertificationCase rCase = RAccessCertificationCase.toRepo(campaignOid, aCase, prismContext);
            session.merge(rCase);

            LOGGER.trace("Access certification case {} merged", rCase);
            casesModified.add(aCase.getId());
        }
    }

    // refresh campaign cases, if requested
    if (RepoModifyOptions.isExecuteIfNoChanges(modifyOptions)) {
        Query query = session.getNamedQuery("get.campaignCases");
        query.setString("ownerOid", campaignOid);
        List<Object> cases = query.list();
        for (Object o : cases) {
            if (!(o instanceof byte[])) {
                throw new IllegalStateException("Certification case: expected byte[], got " + o.getClass());
            }
            byte[] fullObject = (byte[]) o;
            AccessCertificationCaseType aCase = RAccessCertificationCase.createJaxb(fullObject, prismContext,
                    false);
            Long id = aCase.getId();
            if (id != null && casesAddedOrDeleted != null && !casesAddedOrDeleted.contains(id)
                    && !casesModified.contains(id)) {
                RAccessCertificationCase rCase = RAccessCertificationCase.toRepo(campaignOid, aCase,
                        prismContext);
                session.merge(rCase);
                LOGGER.trace("Access certification case {} refreshed", rCase);
            }
        }
    }
}

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

License:Apache License

public int findLastIdInRepo(Session session, String tableOid, String queryName) {
    Query query = session.getNamedQuery(queryName);
    query.setString("oid", tableOid);
    Integer lastId = (Integer) query.uniqueResult();
    if (lastId == null) {
        lastId = 0;/*from w w  w .  ja  va 2  s  .  c  o  m*/
    }
    return lastId;
}

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();// w w  w  .jav  a2 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();//from   www.j a va  2 s  .  co m
}

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.j a v a 2  s .  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;
}