List of usage examples for org.hibernate SQLQuery uniqueResult
R uniqueResult();
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
License:Apache License
public <T extends ObjectType> int countObjectsAttempt(Class<T> type, ObjectQuery query, OperationResult result) {/*w w w . j a va 2 s .c om*/ LOGGER_PERFORMANCE.debug("> count objects {}", new Object[] { type.getSimpleName() }); int count = 0; Session session = null; try { Class<? extends RObject> hqlType = ClassMapper.getHQLTypeClass(type); session = baseHelper.beginReadOnlyTransaction(); Number longCount; if (query == null || query.getFilter() == null) { // this is 5x faster than count with 3 inner joins, it can probably improved also for queries which // filters uses only properties from concrete entities like RUser, RRole by improving interpreter [lazyman] SQLQuery sqlQuery = session.createSQLQuery("SELECT COUNT(*) FROM " + RUtil.getTableName(hqlType)); longCount = (Number) sqlQuery.uniqueResult(); } else { RQuery rQuery; if (isUseNewQueryInterpreter(query)) { QueryEngine2 engine = new QueryEngine2(getConfiguration(), prismContext); rQuery = engine.interpret(query, type, null, true, session); } else { QueryEngine engine = new QueryEngine(getConfiguration(), prismContext); rQuery = engine.interpret(query, type, null, true, session); } longCount = (Number) rQuery.uniqueResult(); } LOGGER.trace("Found {} objects.", longCount); count = longCount != null ? longCount.intValue() : 0; session.getTransaction().commit(); } catch (QueryException | RuntimeException ex) { baseHelper.handleGeneralException(ex, session, result); } finally { baseHelper.cleanupSessionAndResult(session, result); } return count; }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectUpdater.java
License:Apache License
private <T extends ObjectType> String nonOverwriteAddObjectAttempt(PrismObject<T> object, RObject rObject, String originalOid, Session session, OrgClosureManager.Context closureContext) throws ObjectAlreadyExistsException, SchemaException, DtoTranslationException { // check name uniqueness (by type) if (StringUtils.isNotEmpty(originalOid)) { LOGGER.trace("Checking oid uniqueness."); //todo improve this table name bullshit Class hqlType = ClassMapper.getHQLTypeClass(object.getCompileTimeClass()); SQLQuery query = session .createSQLQuery("select count(*) from " + RUtil.getTableName(hqlType) + " where oid=:oid"); query.setString("oid", object.getOid()); Number count = (Number) query.uniqueResult(); if (count != null && count.longValue() > 0) { throw new ObjectAlreadyExistsException("Object '" + object.getCompileTimeClass().getSimpleName() + "' with oid '" + object.getOid() + "' already exists."); }//from w ww. j a va 2 s . c o m } updateFullObject(rObject, object); LOGGER.trace("Saving object (non overwrite)."); String oid = (String) session.save(rObject); lookupTableHelper.addLookupTableRows(session, rObject, false); caseHelper.addCertificationCampaignCases(session, rObject, false); if (closureManager.isEnabled()) { Collection<ReferenceDelta> modifications = createAddParentRefDelta(object); closureManager.updateOrgClosure(null, modifications, session, oid, object.getCompileTimeClass(), OrgClosureManager.Operation.ADD, closureContext); } return oid; }
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. ja va 2s. c om 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 <T extends ObjectType> String nonOverwriteAddObjectAttempt(PrismObject<T> object, ObjectType objectType, RObject rObject, String originalOid, Session session) throws ObjectAlreadyExistsException, SchemaException, DtoTranslationException { // check name uniqueness (by type) if (StringUtils.isNotEmpty(originalOid)) { LOGGER.trace("Checking oid uniqueness."); //todo improve this table name bullshit Class hqlType = ClassMapper.getHQLTypeClass(object.getCompileTimeClass()); SQLQuery query = session .createSQLQuery("select count(*) from " + RUtil.getTableName(hqlType) + " where oid=:oid"); query.setString("oid", object.getOid()); Number count = (Number) query.uniqueResult(); if (count != null && count.longValue() > 0) { throw new ObjectAlreadyExistsException("Object '" + object.getCompileTimeClass().getSimpleName() + "' with oid '" + object.getOid() + "' already exists."); }//from w w w . j av a 2s . c o m } updateFullObject(rObject, object); LOGGER.trace("Saving object (non overwrite)."); String oid = (String) session.save(rObject); //todo finish orgClosureManager //Collection<ReferenceDelta> modifications = createAddParentRefDelta(object); //orgClosureManager.updateOrgClosure(modifications, session, oid, object.getCompileTimeClass(), // OrgClosureManager.Operation.ADD); if (objectType instanceof OrgType || !objectType.getParentOrgRef().isEmpty()) { long time = System.currentTimeMillis(); LOGGER.trace("Org. structure closure table update started."); objectType.setOid(oid); fillHierarchy(rObject, session, true); LOGGER.trace("Org. structure closure table update finished ({} ms).", new Object[] { (System.currentTimeMillis() - time) }); } return oid; }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
private <T extends ObjectType> int countObjectsAttempt(Class<T> type, ObjectQuery query, OperationResult result) {//from w ww. j a va 2 s . c om int count = 0; Session session = null; try { Class<? extends RObject> hqlType = ClassMapper.getHQLTypeClass(type); session = beginReadOnlyTransaction(); Number longCount; if (query == null || query.getFilter() == null) { // this is 5x faster than count with 3 inner joins, it can probably improved also for queries which // filters uses only properties from concrete entities like RUser, RRole by improving interpreter [lazyman] SQLQuery sqlQuery = session.createSQLQuery("SELECT COUNT(*) FROM " + RUtil.getTableName(hqlType)); longCount = (Number) sqlQuery.uniqueResult(); } else { QueryEngine engine = new QueryEngine(getConfiguration(), getPrismContext()); RQuery rQuery = engine.interpret(query, type, null, true, session); longCount = (Number) rQuery.uniqueResult(); } LOGGER.trace("Found {} objects.", longCount); count = longCount != null ? longCount.intValue() : 0; } catch (QueryException | RuntimeException ex) { handleGeneralException(ex, session, result); } finally { cleanupSessionAndResult(session, result); } return count; }
From source file:com.globalsight.everest.workflow.WorkflowJbpmPersistenceHandler.java
License:Apache License
/** * Judges whether the user is rejected for the specified * <code>TaskInstance</code>. <br> * The rejected user will be stored in the table * <code>JBPM_GS_VARIABLE</code>. * /*from w w w . ja va2 s. co m*/ * @param ctx * {@code JbpmContext} * @param userId * the user id. * @param taskInstance * {@code TaskInstance} * @return <code>true</code> when the user is reject by the specified * taskinstance. */ public static boolean isUserRejected(JbpmContext ctx, String userId, TaskInstance taskInstance) { SQLQuery query = null; Session session = ctx.getSession(); query = session.createSQLQuery(SqlHolder.isUserReject); query.setString(VARIABLE_NAME, WorkflowConstants.VARIABLE_IS_REJECTED); query.setString(CATEGORY, VARIABLE_CATEGORY_REJECT); query.setString(ACTOR_ID, userId); query.setLong(TASK_ID, taskInstance.getId()); Number num = (Number) query.uniqueResult(); return num == null ? false : num.longValue() > 0; }
From source file:com.globalsight.everest.workflow.WorkflowJbpmPersistenceHandler.java
License:Apache License
/** * Fix for GBS-1470/*from w w w. j a v a 2s .c o m*/ * Judges whether the user is rejected for (This user Rejected the task first, then reassign to this user) * * @param ctx * {@code JbpmContext} * @param userId * the user id. * @param taskInstance * {@code TaskInstance} * @return <code>true</code> The user reject, and not been reassigned. */ public static boolean isUserRejectedForReassign(JbpmContext ctx, String userId, TaskInstance taskInstance) { SQLQuery query = null; Session session = ctx.getSession(); query = session.createSQLQuery(SqlHolder.isUserRejectForReassign); query.setString(VARIABLE_NAME, WorkflowConstants.VARIABLE_IS_REJECTED); query.setString(CATEGORY, VARIABLE_CATEGORY_REJECT); query.setString(ACTOR_ID, userId); query.setLong(TASK_ID, taskInstance.getId()); long id = taskInstance.getId(); Number num = (Number) query.uniqueResult(); return num == null ? false : num.longValue() > 0; }
From source file:com.globalsight.everest.workflow.WorkflowJbpmPersistenceHandler.java
License:Apache License
/** * Judges whether the task is rejected<br> * The rule for judges the task whether is rejected is as below: * <ul>// ww w. j av a 2s.c o m * <li>If the lp reject the task, the task showed rejected by the lp</li> * <li>If the lp(s) reject the task and there is extra lp availabe for the * task, the task showed rejected for pm</li> * * <li>If the lp(s) reject the task and there is no extra lp availabe for * the task, the task showed availabe for pm</li> * </ul> * * * @param ctx * {@code JbpmContext} * @param taskInstance * {@code TaskInstance} * @param p_pm * The name of the pm * @return <code>true</code> when the task is rejected */ public static boolean isTaskRejected(JbpmContext ctx, TaskInstance taskInstance, String p_pm) { SQLQuery query = null; Session session = ctx.getSession(); query = session.createSQLQuery(SqlHolder.isTaskReject); query.setString(VARIABLE_NAME, WorkflowConstants.VARIABLE_IS_REJECTED); query.setString(CATEGORY, VARIABLE_CATEGORY_REJECT); query.setString(PM, p_pm); query.setLong(TASK_ID, taskInstance.getId()); Number num = (Number) query.uniqueResult(); /* normally, the num should not be null */ return num == null ? false : num.longValue() > 0; }
From source file:com.gp.cong.lcl.common.constant.ExportUnitQueryUtils.java
public boolean isDrAvailableInVoyage(String headerId, String unitSsId) throws Exception { String sb = " select if(count(*)>0,true,false) as result from lcl_unit_ss lus join lcl_booking_piece_unit bu " + " on bu.lcl_unit_ss_id = lus.id join lcl_booking_piece b on b.id= bu.booking_piece_id " + " join lcl_file_number f on f.id = b.file_number_id " + " join lcl_ss_header lsh on lsh.id = lus.ss_header_id where f.state not in ('B') and lsh.id =:headerId"; if (!"0".equalsIgnoreCase(unitSsId)) { sb += " and lus.id=" + unitSsId; }/*from w w w. j av a2s . co m*/ SQLQuery query = getCurrentSession().createSQLQuery(sb); query.setParameter("headerId", headerId); query.addScalar("result", BooleanType.INSTANCE); return (Boolean) query.uniqueResult(); }
From source file:com.gp.cong.logisoft.hibernate.dao.lcl.LclBookingHotCodeDAO.java
public boolean isHotCodeNotExist(String Code, String fileId) throws Exception { SQLQuery query = getCurrentSession() .createSQLQuery("select if(count(*)<1,true,false) as result from lcl_booking_hot_code " + " where code=:code and file_number_id=:fileId"); query.setParameter("fileId", fileId); query.setParameter("code", Code); query.addScalar("result", BooleanType.INSTANCE); return (Boolean) query.uniqueResult(); }