List of usage examples for org.hibernate Session doWork
void doWork(Work work) throws HibernateException;
From source file:com.coroptis.coidi.op.view.integration.StartupTest.java
License:Apache License
public void testLoadInitialData() throws Exception { /**// w ww.j ava2 s.com * Following code is copied from OpModule */ Session session = getService(Session.class); for (final String line : Files.readLines(new File("src/main/resources/data.sql"), Charset.forName("UTF-8"))) { if (line.length() > 0) { logger.debug("executing: " + line); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { connection.createStatement().execute(line); connection.commit(); } }); } } }
From source file:com.ea.core.orm.handle.impl.HibernateSqlORMHandle.java
License:Apache License
@Override protected Object execute(ORMParamsDTO dto) throws Exception { // TODO Auto-generated method stub Session session = this.getHibernateSessionFactory().getCurrentSession(); final ORMParamsDTO tmp = dto; session.doWork(new Work() { @SuppressWarnings("rawtypes") public void execute(Connection connection) throws SQLException { // connectionJDBC // closeconnection System.out.println("sql:" + tmp.getSqlid()); PreparedStatement ps = connection.prepareStatement(tmp.getSqlid()); if (tmp.getParam() != null) { Object data = tmp.getParam(); if (data instanceof Object[]) { Object[] array = (Object[]) data; int index = 1; for (Object obj : array) { setParam(ps, index++, obj); }/*w w w .j a va 2s.c om*/ ps.execute(); } else if (data instanceof Collection) { for (Object array : (Collection) data) { if (array instanceof Object[]) { int index = 1; for (Object obj : (Object[]) array) { setParam(ps, index++, obj); } ps.addBatch(); } else { throw new SQLException("SQL?Object[]???!"); } } ps.executeBatch(); } else { throw new SQLException( "SQL????Object[]???????CollectionObject[]!"); } } } }); return null; }
From source file:com.eclecticlogic.pedal.provider.hibernate.HibernateProviderAccessSpiImpl.java
License:Apache License
@Override public void run(EntityManager entityManager, final Consumer<Connection> work) { Session session = entityManager.unwrap(Session.class); session.doWork(new Work() { @Override//from www .j av a 2s .c om public void execute(Connection connection) throws SQLException { work.accept(connection); } }); }
From source file:com.evolveum.midpoint.repo.sql.ConcurrencyTest.java
License:Apache License
private void concurrencyUniversal(String name, long duration, long waitStep, ModifierThread[] modifierThreads, Checker checker) throws Exception { Session session = getFactory().openSession(); session.doWork(new Work() { @Override//from www . j a v a 2 s.co m public void execute(Connection connection) throws SQLException { System.out.println(">>>>" + connection.getTransactionIsolation()); } }); session.close(); final File file = new File("src/test/resources/concurrency/user.xml"); PrismObject<UserType> user = prismContext.parseObject(file); user.asObjectable().setName(new PolyStringType(name)); OperationResult result = new OperationResult("Concurrency Test"); String oid = repositoryService.addObject(user, null, result); LOGGER.info("*** Object added: " + oid + " ***"); LOGGER.info("*** Starting modifier threads ***"); // modifierThreads[1].setOid(oid); // modifierThreads[1].runOnce(); // if(true) return; for (ModifierThread mt : modifierThreads) { mt.setOid(oid); mt.start(); } LOGGER.info("*** Waiting " + duration + " ms ***"); long startTime = System.currentTimeMillis(); int readIteration = 1; main: while (System.currentTimeMillis() - startTime < duration) { if (checker != null) { checker.check(readIteration, oid); } if (waitStep > 0L) { Thread.sleep(waitStep); } for (ModifierThread mt : modifierThreads) { if (!mt.isAlive()) { LOGGER.error("At least one of threads died prematurely, finishing waiting."); break main; } } readIteration++; } for (ModifierThread mt : modifierThreads) { mt.stop = true; // stop the threads System.out.println("Thread " + mt.id + " has done " + (mt.counter - 1) + " iterations"); LOGGER.info("Thread " + mt.id + " has done " + (mt.counter - 1) + " iterations"); } // we do not have to wait for the threads to be stopped, just examine their results Thread.sleep(1000); // give the threads a chance to finish (before repo will be shut down) for (ModifierThread mt : modifierThreads) { LOGGER.info("Modifier thread " + mt.id + " finished with an exception: ", mt.threadResult); } for (ModifierThread mt : modifierThreads) { AssertJUnit.assertTrue("Modifier thread " + mt.id + " finished with an exception: " + mt.threadResult, mt.threadResult == null); } }
From source file:com.evolveum.midpoint.repo.sql.helpers.BaseHelper.java
License:Apache License
public Session beginTransaction(boolean readOnly) { Session session = getSessionFactory().openSession(); session.beginTransaction();/*from ww w . j av a 2 s.c om*/ if (getConfiguration().getTransactionIsolation() == TransactionIsolation.SNAPSHOT) { LOGGER.trace("Setting transaction isolation level SNAPSHOT."); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { connection.createStatement().execute("SET TRANSACTION ISOLATION LEVEL SNAPSHOT"); } }); } if (readOnly) { // we don't want to flush changes during readonly transactions (they should never occur, // but if they occur transaction commit would still fail) session.setFlushMode(FlushMode.MANUAL); LOGGER.trace("Marking transaction as read only."); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { connection.createStatement().execute("SET TRANSACTION READ ONLY"); } }); } return session; }
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; }/*www. ja va2 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 String computeDeltaTable(List<Edge> edges, Context context, Session session) { if (edges.isEmpty()) { throw new IllegalArgumentException("No edges to add/remove"); }//from ww w.j a v a 2s .c o m String deltaTempTableName; if (context.temporaryTableName != null) { deltaTempTableName = context.temporaryTableName; // table was created on the beginning of trasaction } else if (isOracle()) { deltaTempTableName = TEMP_DELTA_TABLE_NAME_FOR_ORACLE; // table definition is global } else { deltaTempTableName = generateDeltaTempTableName(); // table will be created now } if (COUNT_CLOSURE_RECORDS && LOGGER.isTraceEnabled()) { Query q = session.createSQLQuery("select count(*) from " + CLOSURE_TABLE_NAME); List list = q.list(); LOGGER.trace("OrgClosure has {} rows", list.toString()); } long start; int count; String selectClause = "select t1.descendant_oid as descendant_oid, t2.ancestor_oid as ancestor_oid, " + "sum(t1.val*t2.val) as val " + "from " + CLOSURE_TABLE_NAME + " t1, " + CLOSURE_TABLE_NAME + " t2 " + "where " + getWhereClause(edges) + " " + "group by t1.descendant_oid, t2.ancestor_oid"; if (isSQLServer()) { // we create the table manually, because we want to have an index on it, and // with serializable transactions it is not possible to create index within the transaction (after inserting data) start = System.currentTimeMillis(); final String createTableSql = "create table " + deltaTempTableName + " (" + "descendant_oid NVARCHAR(36) COLLATE database_default, " + "ancestor_oid NVARCHAR(36) COLLATE database_default, " + "val INT, " + "PRIMARY KEY (descendant_oid, ancestor_oid))"; // Query createTableQuery = session.createSQLQuery(createTableSql); // createTableQuery.executeUpdate(); <--- this does not work because the temporary table gets deleted when the command terminates (preparedStatement issue - maybe something like this: https://support.microsoft.com/en-us/kb/280134 ?) session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { connection.createStatement().execute(createTableSql); } }); if (LOGGER.isTraceEnabled()) LOGGER.trace("Empty delta table created in {} ms", System.currentTimeMillis() - start); Query insertQuery = session.createSQLQuery("insert into " + deltaTempTableName + " " + selectClause); start = System.currentTimeMillis(); count = insertQuery.executeUpdate(); } else { String createTablePrefix; if (isPostgreSQL()) { createTablePrefix = "create local temporary table " + deltaTempTableName + " on commit drop as "; } else if (isH2()) { // todo skip if this is first in this transaction Query q = session.createSQLQuery("delete from " + deltaTempTableName); int c = q.executeUpdate(); LOGGER.trace("Deleted {} rows from temporary table {}", c, deltaTempTableName); createTablePrefix = "insert into " + deltaTempTableName + " "; } else if (isMySQL()) { createTablePrefix = "create temporary table " + deltaTempTableName + " engine=memory as "; // engine=memory is questionable because of missing tansactionality (but the transactionality is needed in the main table, not the delta table...) } else if (isOracle()) { // todo skip if this is first in this transaction Query q = session.createSQLQuery("delete from " + deltaTempTableName); int c = q.executeUpdate(); LOGGER.trace("Deleted {} rows from temporary table {}", c, deltaTempTableName); createTablePrefix = "insert into " + deltaTempTableName + " "; } else { throw new UnsupportedOperationException("define other databases"); } Query query1 = session.createSQLQuery(createTablePrefix + selectClause); start = System.currentTimeMillis(); count = query1.executeUpdate(); } if (LOGGER.isTraceEnabled()) LOGGER.trace("Added {} records to temporary delta table {} ({} ms).", new Object[] { count, deltaTempTableName, System.currentTimeMillis() - start }); if (isPostgreSQL()) { start = System.currentTimeMillis(); Query qIndex = session.createSQLQuery("CREATE INDEX " + deltaTempTableName + "_idx " + " ON " + deltaTempTableName + " USING btree " + " (descendant_oid, ancestor_oid)"); qIndex.executeUpdate(); if (LOGGER.isTraceEnabled()) LOGGER.trace("Index created in {} ms", System.currentTimeMillis() - start); } // TODO index for MySQL !!! if (DUMP_TABLES) dumpOrgClosureTypeTable(session, CLOSURE_TABLE_NAME); if (DUMP_TABLES) dumpOrgClosureTypeTable(session, deltaTempTableName); // TODO drop delta table in case of exception return deltaTempTableName; }
From source file:com.evolveum.midpoint.repo.sql.SequenceTest.java
License:Apache License
private void concurrencyUniversal(String name, String sequenceFileName, long duration, WorkerThread[] workerThreads, boolean alwaysOrder) throws Exception { Session session = getFactory().openSession(); session.doWork(new Work() { @Override/*from ww w. j a v a2 s . c o m*/ public void execute(Connection connection) throws SQLException { System.out.println(">>>>" + connection.getTransactionIsolation()); } }); session.close(); final File file = new File(TEST_DIR + sequenceFileName); PrismObject<SequenceType> sequence = prismContext.parseObject(file); sequence.asObjectable().setName(new PolyStringType(name)); OperationResult result = new OperationResult("Concurrency Test"); String oid = repositoryService.addObject(sequence, null, result); LOGGER.info("*** Object added: " + oid + " ***"); LOGGER.info("*** Starting modifier threads ***"); for (WorkerThread t : workerThreads) { t.setOid(oid); t.start(); } LOGGER.info("*** Waiting " + duration + " ms ***"); Thread.sleep(duration); for (WorkerThread t : workerThreads) { t.stop = true; } long endTime = System.currentTimeMillis() + STOP_TIMEOUT; for (;;) { long remaining = endTime - System.currentTimeMillis(); if (remaining <= 0) { break; } for (WorkerThread t : workerThreads) { t.join(remaining); remaining = endTime - System.currentTimeMillis(); if (remaining <= 0) { break; } } } for (WorkerThread t : workerThreads) { LOGGER.info("Worker thread {} finished after {} iterations with result: {}", t.id, t.counter, t.threadResult != null ? t.threadResult : "OK"); } for (WorkerThread t : workerThreads) { if (t.threadResult != null) { throw new AssertionError("Worker thread " + t.id + " finished with an exception: " + t.threadResult, t.threadResult); } } List<Long> allValues = new ArrayList<>(); for (WorkerThread t : workerThreads) { allValues.addAll(t.values); } if (alwaysOrder || workerThreads.length > 1) { Collections.sort(allValues); } LOGGER.trace("Checking a list of {} values", allValues.size()); for (int i = 0; i < allValues.size(); i++) { if (allValues.get(i) != i) { LOGGER.error("Incorrect value at position {}: {}", i, allValues.get(i)); for (WorkerThread t : workerThreads) { LOGGER.info("Thread {}: {}", t.id, t.values); } fail("Incorrect value at position " + i + ": " + allValues.get(i)); } } }
From source file:com.evolveum.midpoint.repo.sql.SqlAuditServiceImpl.java
License:Apache License
/** * This method creates temporary table for cleanup audit method. * * @param session/* w w w. j a va 2 s . c om*/ * @param dialect * @param tempTable */ private void createTemporaryTable(Session session, final Dialect dialect, final String tempTable) { session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { //check if table exists try { Statement s = connection.createStatement(); s.execute("select id from " + tempTable + " where id = 1"); //table already exists return; } catch (Exception ex) { //we expect this on the first time } StringBuilder sb = new StringBuilder(); sb.append(dialect.getCreateTemporaryTableString()); sb.append(' ').append(tempTable).append(" (id "); sb.append(dialect.getTypeName(Types.BIGINT)); sb.append(" not null)"); sb.append(dialect.getCreateTemporaryTablePostfix()); Statement s = connection.createStatement(); s.execute(sb.toString()); } }); }
From source file:com.evolveum.midpoint.repo.sql.SqlBaseService.java
License:Apache License
protected Session beginTransaction(boolean readOnly) { Session session = getSessionFactory().openSession(); session.beginTransaction();//from w w w . j ava 2s . com if (getConfiguration().getTransactionIsolation() == TransactionIsolation.SNAPSHOT) { LOGGER.trace("Setting transaction isolation level SNAPSHOT."); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { connection.createStatement().execute("SET TRANSACTION ISOLATION LEVEL SNAPSHOT"); } }); } if (readOnly) { // we don't want to flush changes during readonly transactions (they should never occur, // but if they occur transaction commit would still fail) session.setFlushMode(FlushMode.MANUAL); LOGGER.trace("Marking transaction as read only."); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { connection.createStatement().execute("SET TRANSACTION READ ONLY"); } }); } return session; }