List of usage examples for org.hibernate Session createSQLQuery
@Override NativeQuery createSQLQuery(String queryString);
From source file:com.evolveum.midpoint.repo.sql.closure.AbstractOrgClosureTest.java
License:Apache License
protected boolean checkClosureMatrix() { Session session = getSession(); // we compute the closure table "by hand" as 1 + A + A^2 + A^3 + ... + A^n where n is the greatest expected path length int vertices = getVertices().size(); long start = System.currentTimeMillis(); // used to give indices to vertices List<String> vertexList = new ArrayList<>(getVertices()); if (DUMP_TC_MATRIX_DETAILS) LOGGER.info("Vertex list = {}", vertexList); DoubleMatrix2D a = new SparseDoubleMatrix2D(vertices, vertices); // for (int i = 0; i < vertices; i++) { // a.setQuick(i, i, 1.0); // }//from w w w. ja va2 s . c om for (DefaultEdge edge : orgGraph.edgeSet()) { a.set(vertexList.indexOf(orgGraph.getEdgeSource(edge)), vertexList.indexOf(orgGraph.getEdgeTarget(edge)), 1.0); } DoubleMatrix2D result = new SparseDoubleMatrix2D(vertices, vertices); for (int i = 0; i < vertices; i++) { result.setQuick(i, i, 1.0); } DoubleMatrix2D power = result.copy(); Algebra alg = new Algebra(); for (int level = 1; level <= maxLevel; level++) { power = alg.mult(power, a); result.assign(power, Functions.plus); // System.out.println("a=" + a); // System.out.println("a^"+level+"="+power); } LOGGER.info("TC matrix computed in {} ms", System.currentTimeMillis() - start); if (DUMP_TC_MATRIX_DETAILS) LOGGER.info("TC matrix expected = {}", result); Query q = session.createSQLQuery("select descendant_oid, ancestor_oid, val from m_org_closure") .addScalar("descendant_oid", StringType.INSTANCE).addScalar("ancestor_oid", StringType.INSTANCE) .addScalar("val", LongType.INSTANCE); List<Object[]> list = q.list(); LOGGER.info("OrgClosure has {} rows", list.size()); DoubleMatrix2D closureInDatabase = new SparseDoubleMatrix2D(vertices, vertices); for (Object[] item : list) { int val = Integer.parseInt(item[2].toString()); if (val == 0) { throw new IllegalStateException("Row with val == 0 in closure table: " + list); } closureInDatabase.set(vertexList.indexOf(item[0]), vertexList.indexOf(item[1]), val); } if (DUMP_TC_MATRIX_DETAILS) LOGGER.info("TC matrix fetched from db = {}", closureInDatabase); double zSumResultBefore = result.zSum(); double zSumClosureInDb = closureInDatabase.zSum(); result.assign(closureInDatabase, Functions.minus); double zSumResultAfter = result.zSum(); LOGGER.info("Summary of items in closure computed: {}, in DB-stored closure: {}, delta: {}", new Object[] { zSumResultBefore, zSumClosureInDb, zSumResultAfter }); if (DUMP_TC_MATRIX_DETAILS) LOGGER.info("Difference matrix = {}", result); boolean problem = false; for (int i = 0; i < vertices; i++) { for (int j = 0; j < vertices; j++) { double delta = result.get(i, j); if (Math.round(delta) != 0) { System.err.println("delta(" + vertexList.get(i) + "," + vertexList.get(j) + ") = " + delta + " (closureInDB=" + closureInDatabase.get(i, j) + ", expected=" + (result.get(i, j) + closureInDatabase.get(i, j)) + ")"); LOGGER.error("delta(" + vertexList.get(i) + "," + vertexList.get(j) + ") = " + delta); problem = true; } } } if (problem) { checkOrgGraph(); } return problem; }
From source file:com.evolveum.midpoint.repo.sql.DeleteTest.java
License:Apache License
@Test public void delete0003() throws Exception { PrismObject<ShadowType> shadow = prismContext.parseObject(new File(FOLDER_BASE, "delete/shadow.xml")); OperationResult result = new OperationResult("add shadow"); final String oid = repositoryService.addObject(shadow, null, result); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, oid, null, result); shadow = prismContext.parseObject(new File(FOLDER_BASE, "delete/shadow.xml")); AssertJUnit.assertEquals(shadow, repoShadow); repositoryService.deleteObject(ShadowType.class, oid, result); result.recomputeStatus();/*from w w w.j a v a 2s . c o m*/ AssertJUnit.assertTrue(result.isSuccess()); Session session = getFactory().openSession(); try { SQLQuery query = session.createSQLQuery("select count(*) from m_trigger where owner_oid = ?"); query.setString(0, oid); Number count = (Number) query.uniqueResult(); AssertJUnit.assertEquals(count.longValue(), 0L); } finally { session.close(); } }
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); }/* www .ja v a2 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.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.co 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 <T extends ObjectType> int countObjectsAttempt(Class<T> type, ObjectQuery query, OperationResult result) {/*from w w w .ja va 2 s . c o m*/ 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 w w . j a v a 2s . co 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.helpers.OrgClosureManager.java
License:Apache License
private Context onBeginTransaction(Session session) { // table locking if (isH2() || isOracle() || isSQLServer()) { lockClosureTable(session);/*from w ww . j ava 2 s. c om*/ } // other Context ctx = new Context(); if (isH2()) { ctx.temporaryTableName = generateDeltaTempTableName(); String createTableQueryText = "create temporary table " + ctx.temporaryTableName + " (\n" + " descendant_oid VARCHAR(36) NOT NULL,\n" + " ancestor_oid VARCHAR(36) NOT NULL,\n" + " val INTEGER NOT NULL,\n" + " PRIMARY KEY (descendant_oid, ancestor_oid)\n" + ")"; long start = System.currentTimeMillis(); Query q = session.createSQLQuery(createTableQueryText); q.executeUpdate(); LOGGER.trace("Temporary table {} created in {} ms", ctx.temporaryTableName, System.currentTimeMillis() - start); } return ctx; }
From source file:com.evolveum.midpoint.repo.sql.helpers.OrgClosureManager.java
License:Apache License
public void cleanUpAfterOperation(Context closureContext, Session session) { if (closureContext == null) { return;//from w w w.j a va 2s .c o m } if (closureContext.temporaryTableName == null) { return; } if (isH2()) { // beware, this does implicit commit! Query dropQuery = session.createSQLQuery("drop table if exists " + closureContext.temporaryTableName); dropQuery.executeUpdate(); closureContext.temporaryTableName = null; } }
From source file:com.evolveum.midpoint.repo.sql.helpers.OrgClosureManager.java
License:Apache License
private boolean autoUpdateClosureTableStructure() { if (baseHelper.getConfiguration().isSkipOrgClosureStructureCheck()) { LOGGER.debug("Skipping org closure structure check."); return false; }// ww w .j a v a2 s . c om SessionFactory sf = baseHelper.getSessionFactory(); if (sf instanceof SessionFactoryImpl) { SessionFactoryImpl sfi = ((SessionFactoryImpl) sf); LOGGER.debug("SessionFactoryImpl.getSettings() = {}; auto update schema = {}", sfi.getSettings(), sfi.getSettings() != null ? sfi.getSettings().isAutoUpdateSchema() : null); if (sfi.getSettings() != null && sfi.getSettings().isAutoUpdateSchema()) { LOGGER.info("Checking the closure table structure."); final Session session = baseHelper.getSessionFactory().openSession(); final Holder<Boolean> wrongNumberOfColumns = new Holder<>(false); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { DatabaseMetaData meta = connection.getMetaData(); if (meta == null) { LOGGER.warn("No database metadata found."); } else { ResultSet rsColumns = meta.getColumns(null, null, CLOSURE_TABLE_NAME, null); int columns = 0; while (rsColumns.next()) { LOGGER.debug("Column: {} {}", rsColumns.getString("TYPE_NAME"), rsColumns.getString("COLUMN_NAME")); columns++; } if (columns > 0) { LOGGER.debug("There are {} columns in {} (obtained via DatabaseMetaData)", columns, CLOSURE_TABLE_NAME); if (columns != 3) { wrongNumberOfColumns.setValue(true); } return; } // perhaps some problem here... let's try another way out try { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select * from " + CLOSURE_TABLE_NAME); int cols = rs.getMetaData().getColumnCount(); if (cols > 0) { LOGGER.debug( "There are {} columns in {} (obtained via resultSet.getMetaData())", cols, CLOSURE_TABLE_NAME); if (cols != 3) { wrongNumberOfColumns.setValue(true); } } else { LOGGER.warn( "Couldn't determine the number of columns in {}. In case of problems, please fix your database structure manually using DB scripts in 'config' folder.", CLOSURE_TABLE_NAME); } rs.close(); // don't care about closing them in case of failure stmt.close(); } catch (RuntimeException e) { LoggingUtils.logException(LOGGER, "Couldn't obtain the number of columns in {}. In case of problems running midPoint, please fix your database structure manually using DB scripts in 'config' folder.", e, CLOSURE_TABLE_NAME); } } } }); if (wrongNumberOfColumns.getValue()) { session.getTransaction().begin(); LOGGER.info("Wrong number of columns detected; dropping table " + CLOSURE_TABLE_NAME); Query q = session.createSQLQuery("drop table " + CLOSURE_TABLE_NAME); q.executeUpdate(); session.getTransaction().commit(); LOGGER.info( "Calling hibernate hbm2ddl SchemaUpdate tool to create the table in the necessary form."); new SchemaUpdate(sfi.getServiceRegistry(), baseHelper.getSessionFactoryBean().getConfiguration()).execute(false, true); LOGGER.info( "Done, table was (hopefully) created. If not, please fix your database structure manually using DB scripts in 'config' folder."); return true; } } else { // auto schema update is disabled } } else { LOGGER.warn("SessionFactory is not of type SessionFactoryImpl; it is {}", sf != null ? sf.getClass() : "null"); } return false; }
From source file:com.evolveum.midpoint.repo.sql.helpers.OrgClosureManager.java
License:Apache License
private void rebuild(boolean check, boolean rebuild, boolean stopOnFailure, final Context context, final Session session, OperationResult result) throws SchemaException { List existingEntries = null;//w ww . j a v a2 s . c o m if (check) { LOGGER.info("Reading from existing org closure table"); Query selectQuery = session .createSQLQuery("SELECT descendant_oid, ancestor_oid, val from " + CLOSURE_TABLE_NAME) .addScalar("descendant_oid", StringType.INSTANCE).addScalar("ancestor_oid", StringType.INSTANCE) .addScalar("val", IntegerType.INSTANCE); existingEntries = selectQuery.list(); LOGGER.info("{} entries read", existingEntries.size()); } LOGGER.info("Computing org closure table from scratch"); Query deleteQuery = session.createSQLQuery("delete from " + CLOSURE_TABLE_NAME); deleteQuery.executeUpdate(); LOGGER.trace("Closure table content deleted"); final int orgsTotal = repositoryService.countObjects(OrgType.class, new ObjectQuery(), result); final MutableInt orgsProcessed = new MutableInt(0); ResultHandler<OrgType> handler = new ResultHandler<OrgType>() { @Override public boolean handle(PrismObject<OrgType> object, OperationResult parentResult) { LOGGER.trace("Processing {}", object); handleAdd(object.getOid(), getParentOidsFromObject(object), context, session); orgsProcessed.add(1); int currentState = orgsProcessed.intValue(); if (currentState % 100 == 0) { LOGGER.info("{} organizations processed (out of {})", currentState, orgsTotal); } return true; } }; repositoryService.searchObjectsIterative(OrgType.class, new ObjectQuery(), handler, null, false, result); LOGGER.info( "Org closure table was successfully recomputed (not committed yet); all {} organizations processed", orgsTotal); if (check) { LOGGER.info("Reading from recomputed org closure table"); Query selectQuery = session .createSQLQuery("SELECT descendant_oid, ancestor_oid, val from " + CLOSURE_TABLE_NAME) .addScalar("descendant_oid", StringType.INSTANCE).addScalar("ancestor_oid", StringType.INSTANCE) .addScalar("val", IntegerType.INSTANCE); List recomputedEntries = selectQuery.list(); LOGGER.info("{} entries read", recomputedEntries.size()); compareOrgClosureTables(existingEntries, recomputedEntries, rebuild, result); } else { result.recordSuccess(); } }