@Transactional(readOnly = false) public void executeBatch(final String sql, final Object[]... parameters) { getSession().doWork(new Work() { public void execute(Connection connection) throws SQLException { connection.setAutoCommit(false); PreparedStatement stmt = connection.prepareStatement(sql); for (Object[] arr : parameters) { int i = 1; for (Object p : arr) { stmt.setObject(i++, p); } stmt.addBatch(); } stmt.executeBatch(); connection.commit(); } }); }
public boolean tableExists(Session session, final String table) { final ExtendedDialect locDialect = (ExtendedDialect) this.dialect; final Boolean[] hasTable = new Boolean[1]; session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { ResultSet tables = connection.getMetaData().getTables(null, defaultSchema, locDialect.getNameForMetadataQuery(table, false), new String[]{"TABLE"}); try { hasTable[0] = tables.next(); } finally { tables.close(); } } }); return hasTable[0]; }
@Before public void initializeDatabase() { Session session = entityManager.unwrap(Session.class); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { try { File script = new File(getClass().getResource("/data.sql").getFile()); RunScript.execute(connection, new FileReader(script)); } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("Database initialize script error"); } } }); }
/** * Initializes, or upgrades the current QuartzDesk database schema by * executing the specified list of SQL scripts. * * @param scriptUrls the list of SQL scripts to execute. * @param schemaVersion the version of the schema after the specified SQL scripts have been applied. */ public void initializeOrUpgradeSchema( final List<URL> scriptUrls, final Version schemaVersion ) { Session session = getSessionFactory().getCurrentSession(); session.doWork( new Work() { @Override public void execute( Connection connection ) throws SQLException { DatabaseScriptExecutor scriptExecutor = new DatabaseScriptExecutor(); scriptExecutor.addScriptUrls( scriptUrls ); scriptExecutor.executeScripts( connection ); SchemaUpdate schemaUpdate = new SchemaUpdate() .withMajor( schemaVersion.getMajor() ) .withMinor( schemaVersion.getMinor() ) .withMaintenance( schemaVersion.getMaintenance() ) .withAppliedAt( Calendar.getInstance() ); insertSchemaUpdate( schemaUpdate ); } } ); }
/** * List tables from database */ private List<String> listTables(Session session) { final List<String> tables = new ArrayList<String>(); final String[] tableTypes = {"TABLE"}; final String[] tablePatterns = new String[]{"JBPM_%", "OKM_%", "DEFAULT_%", "VERSION_%", "jbpm_%", "okm_%", "default_%", "version_%"}; session.doWork(new Work() { @Override public void execute(Connection con) throws SQLException { DatabaseMetaData md = con.getMetaData(); for (String table : tablePatterns) { ResultSet rs = md.getTables(null, null, table, tableTypes); while (rs.next()) { tables.add(rs.getString(3)); } rs.close(); } } }); return tables; }
/** * Executes the passed sql files on the EntityManager. * * @param entityManager * the EntityManager * @param sqlScripts * sql scripts to execute */ public static void insertSqlFile(EntityManager entityManager, final File... sqlScripts) { entityManager.unwrap(Session.class).doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { // Setup database try { for (File file : sqlScripts) { LOGGER.debug("INSERTing {}", file.getAbsolutePath()); Assume.assumeTrue("SQL-Script not found", file.isFile()); String sql = Resources.toString(file.toURI().toURL(), Charsets.UTF_8); executeSqlScript(connection, file.getName(), sql); LOGGER.debug("INSERTing {} ... done", file.getAbsolutePath()); } } catch (IOException | ScriptException e) { throw new SQLException(e); } } }); }
/** * Executes the passed sql queries on the EntityManager. * * @param entityManager * the EntityManager * * @param sqlQuery * queries to execute */ public static void insertSqlString(EntityManager entityManager, final String... sqlQuery) { entityManager.unwrap(Session.class).doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { // Setup database try { for (String query : sqlQuery) { LOGGER.debug("INSERTing '{}'", query); executeSqlScript(connection, null, query); LOGGER.debug("INSERTing '{}' ... done", query); } } catch (ScriptException e) { throw new SQLException(e); } } }); }
/** * Inserts test data in DbUnit XML format. * * @param entityManager * the EntityManager * @param dbUnitTestdata * test file stream */ public static void insertDbUnitTestdata(EntityManager entityManager, final InputStream dbUnitTestdata) { entityManager.unwrap(Session.class).doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { // Insert Testdata try { LOGGER.debug("INSERTing testdata"); DatabaseConnection databaseConnection = new DatabaseConnection(connection); databaseConnection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory()); FlatXmlDataSet dataSet = new FlatXmlDataSet( new FlatXmlProducer(new InputSource(dbUnitTestdata), false, true)); DatabaseOperation.CLEAN_INSERT.execute(databaseConnection, dataSet); LOGGER.debug("INSERTing testdata ... done"); } catch (DatabaseUnitException e) { throw new SQLException(e); } } }); }
@Override public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException { Session session = (Session) entityManager.getDelegate(); if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) { getSession(entityManager).getTransaction().setTimeout(definition.getTimeout()); } entityManager.getTransaction().begin(); logger.debug("Transaction started"); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { logger.debug("The connection instance is " + connection.toString()); logger.debug("The isolation level of the connection is " + connection.getTransactionIsolation() + " and the isolation level set on the transaction is " + definition.getIsolationLevel() ); DataSourceUtils.prepareConnectionForTransaction(connection, definition); } }); return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName()); }
/** * <p>Check table and sequence naming. Important because sequence handling is customized through * {@link PerTableSequenceStyleGenerator} and {@link PerTableSequenceStrategyProvider}.</p> * * <p>We check that {@link Person} entity creates a {@code person} table and a {@code person_id_seq} sequence.</p> */ @Test public void testTablesAndSequences() { EntityManager entityManager = entityManagerUtils.getEntityManager(); ((Session) entityManager.getDelegate()).doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { String expectedTableName = Person.class.getSimpleName().toLowerCase(); // person String expectedSequenceName = expectedTableName + "_id_seq"; // person_id_seq JdbcRelation table = getRelation(connection, configurationProvider.getDefaultSchema(), expectedTableName, JdbcDatabaseMetaDataConstants.REL_TYPE_TABLE); Assert.assertEquals(expectedTableName, table.getTable_name()); JdbcRelation sequence = getRelation(connection, configurationProvider.getDefaultSchema(), expectedSequenceName, JdbcDatabaseMetaDataConstants.REL_TYPE_SEQUENCE); Assert.assertEquals(expectedSequenceName, sequence.getTable_name()); } }); }
@Test public void openSession() throws Exception { createSessionFactory(); // Session session = sessionFactory.openSession(); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { System.out.println("connection: " + connection); System.out.println("autoCommit: " + connection.getAutoCommit()); System.out.println("transactionIsolation: " + connection.getTransactionIsolation()); } }); System.out.println("flushMode: " + session.getFlushMode());//FlushMode.AUTO System.out.println(session); assertNotNull(session); }
@Test public void openSession() throws Exception { createSessionFactory(); // Session session = sessionFactory.openSession(); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { System.out.println("connection: " + connection); System.out.println("autoCommit: " + connection.getAutoCommit()); System.out.println("transactionIsolation: " + connection.getTransactionIsolation()); } }); System.out.println("flushMode: " + session.getFlushMode()); System.out.println(session); assertNotNull(session); }
@Test public void openSession() throws Exception { Configuration config = new Configuration().configure("hibernate.cfg.xml"); // SessionFactory sessionFactory = config.buildSessionFactory(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()) .buildServiceRegistry(); SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); System.out.println("sessionFactory: " + sessionFactory); Session session = sessionFactory.openSession(); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { System.out.println("connection: " + connection); System.out.println("getAutoCommit: " + connection.getAutoCommit()); System.out.println("getTransactionIsolation: " + connection.getTransactionIsolation()); } }); }
@Override public Object beginTransaction(EntityManager entityManager, final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException { Session session = entityManager.unwrap(Session.class); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { DataSourceUtils.prepareConnectionForTransaction(connection, definition); if (connection.isReadOnly() && !definition.isReadOnly()) { connection.setReadOnly(false); } } }); entityManager.getTransaction().begin(); return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName()); }
public void runScript() { getSession().doWork(new Work() { public void execute(Connection conn) throws SQLException { if(JdbcHelper.isExec(conn)) { return; } try { String databaseType = JdbcHelper.getDatabaseType(conn); String schema = "db/core/schema-" + databaseType + ".sql"; ScriptRunner runner = new ScriptRunner(conn, true); runner.runScript(schema); } catch (Exception e) { throw new SnakerException(e); } } }); }
public static void assertTableHasColumn(EntityManager manager, final String tableName, final String columnName) { SessionImpl session = (SessionImpl) manager.unwrap(Session.class); final ResultCollector rc = new ResultCollector(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { ResultSet columns = connection.getMetaData().getColumns(null, null, tableName.toUpperCase(), null); while(columns.next()) { if (columns.getString(4).toUpperCase().equals(columnName.toUpperCase())) { rc.found=true; } } } }); if (!rc.found) { fail("Column [" + columnName + "] not found on table : " + tableName); } }
public static void assertTableExists(EntityManager manager, final String name) { SessionImpl session = (SessionImpl) manager.unwrap(Session.class); final ResultCollector rc = new ResultCollector(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { ResultSet tables = connection.getMetaData().getTables(null, null, "%", null); while(tables.next()) { if (tables.getString(3).toUpperCase().equals(name.toUpperCase())) { rc.found=true; } } } }); if (!rc.found) { fail("Table not found in schema : " + name); } }
private void init(HibernateEntityManager hem) { hem.getSession().doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { String dbName = connection.getMetaData().getDatabaseProductName(); if (dbName.equals(MSSQLDialect.PRODUCT_NAME)) { dialect = new MSSQLDialect(); } else if (dbName.equals(PostgresDialect.PRODUCT_NAME)) { dialect = new PostgresDialect(); } else if (dbName.equals(H2Dialect.PRODUCT_NAME)) { dialect = new H2Dialect(); } else if (dbName.equals(MySQLDialect.PRODUCT_NAME)) { dialect = new MySQLDialect(); } else { dialect = new DefaultDialect(); } } }); }
/** * {@inheritDoc} */ @Override public <RowT> List<RowT> query(final User user, final Filter filter, final List<SiteOrder> orderings, final SiteProjectionBinder<RowT> binder, final int retrieve, final int offset, final int limit) { final List<RowT> list = new ArrayList<RowT>(); final Session session = AbstractDAO.getSession(em()); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { SqlSiteTableDAO dao = new SqlSiteTableDAO(connection, dialect); list.addAll(dao.query(user, filter, orderings, binder, retrieve, offset, limit)); } }); return list; }
public static void callProcedure(Persistence persistence, final String sql) { getSession().doWork(new Work() { public void execute(Connection connection) throws SQLException { CallableStatement procStatement = null; try { System.err.println(sql); procStatement = connection.prepareCall(sql); procStatement.execute(); } catch (Exception e) { e.printStackTrace(); } finally { if (null != procStatement) { procStatement.close(); } } } }); }
/** * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported by * {@link PreparedStatement}. <br> * INSERT UPDATE DELETE DROP CREATE ALTER TRUNCATE RENAME sueprpan add * * @param session the session * @param queryString the query * @param parameters parameters to substitute in the query * @return the results of the query as an Object[] (an array cell per column) */ public static int runSqlDml(Session session, final String queryString, final Object[] parameters) { final List<Integer> result = new ArrayList<Integer>(); try { session.doWork(new Work() { public void execute(Connection connection) throws SQLException { Statement stmt = connection.createStatement(); try { result.add(stmt.executeUpdate(queryString)); } finally { stmt.close(); } } }); } catch (HibernateException e) { result.add(-1); session.getTransaction().rollback(); session.beginTransaction(); throw e; } if (result.size() > 0) { return result.get(0); } return -1; }
public static void callProcedure(Persistence persistence, final String sql) { Session session = persistence.getSession(getDbName()); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { CallableStatement procStatement = null; try { System.err.println(sql); procStatement = connection.prepareCall(sql); procStatement.execute(); } catch (Exception e) { e.printStackTrace(); } finally { if (null != procStatement) { procStatement.close(); } } } }); }
private void insertNewRow(Session session) { session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement statement = null; try { statement = connection.createStatement(); statement.executeUpdate("INSERT INTO sequenceIdentifier VALUES NEXT VALUE FOR hibernate_sequence"); } finally { if (statement != null) { statement.close(); } } } }); }
@Test public void test() { Session session = null; Transaction txn = null; try { session = getSessionFactory().openSession(); txn = session.beginTransaction(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { LOGGER.debug("Transaction isolation level is {}", Environment.isolationLevelToString(connection.getTransactionIsolation())); } }); txn.commit(); } catch (RuntimeException e) { if ( txn != null && txn.isActive() ) txn.rollback(); throw e; } finally { if (session != null) { session.close(); } } }
@Transactional(readOnly = false) public void executeBatch(final String[] sqlList) { getSession().doWork(new Work() { public void execute(Connection connection) throws SQLException { connection.setAutoCommit(false); Statement stmt = connection.createStatement(); for (String sql : sqlList) { stmt.addBatch(sql); } stmt.executeBatch(); connection.commit(); } }); }
public List<String> getAddNotNullSQLIfRequired(Session session, String tableName, String... columns) { final Table table = findTable(tableName); final List<String> sqlStrings = new ArrayList<String>(); final Set<String> colset = new HashSet<String>(Arrays.asList(columns)); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { ResultSet colresult = connection.getMetaData().getColumns(getDefaultCatalog(), extDialect.getNameForMetadataQuery(getDefaultSchema(), false), extDialect.getNameForMetadataQuery(table.getName(), table.isQuoted()), "%"); try { while( colresult.next() ) { String columnName = colresult.getString("COLUMN_NAME").toLowerCase(); if( colset.contains(columnName) && "yes".equals(colresult.getString("IS_NULLABLE").toLowerCase()) ) { Column column = table.getColumn(new Column(columnName)); StringBuffer alter = new StringBuffer("alter table ") .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)).append(' ') .append(extDialect.getAddNotNullSql(mapping, column)); sqlStrings.add(alter.toString()); } } } finally { colresult.close(); } } }); return sqlStrings; }
@Override protected int countDataMigrations(final HibernateMigrationHelper helper, Session session) { final int[] ctr = new int[]{0}; session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { final DatabaseMetaData metaData = connection.getMetaData(); final String defaultCatalog = helper.getDefaultCatalog(); final String defaultSchema = helper.getDefaultSchema(); final ResultSet tableSet = metaData.getTables(defaultCatalog, defaultSchema, null, new String[]{"TABLE"}); try { while( tableSet.next() ) { ctr[0]++; } } finally { tableSet.close(); } } }); return ctr[0]; }
@Override public void doWork(final Work work) throws HibernateException { WorkExecutorVisitable<Void> realWork = new WorkExecutorVisitable<Void>() { @Override public Void accept(WorkExecutor<Void> workExecutor, Connection connection) throws SQLException { workExecutor.executeWork( work, connection ); return null; } }; doWork( realWork ); }
@Override public void emite() { // we CAN'T close the resource, as it's managed by Hibernate @SuppressWarnings("resource") Session session = manager.unwrap(Session.class); Work work = new EmissorRelatorioWork(this.emissor); session.doWork(work); }
@Override public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException { Session session = (Session) entityManager.getDelegate(); if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) { getSession(entityManager).getTransaction().setTimeout( definition.getTimeout()); } final TransactionData data = new TransactionData(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Integer previousIsolationLevel = DataSourceUtils .prepareConnectionForTransaction(connection, definition); data.setPreviousIsolationLevel(previousIsolationLevel); data.setConnection(connection); } }); entityManager.getTransaction().begin(); Object springTransactionData = prepareTransaction(entityManager, definition.isReadOnly(), definition.getName()); data.setSpringTransactionData(springTransactionData); return data; }
/** * Import mime types into database */ private void importMimeTypes(String userId, HttpServletRequest request, HttpServletResponse response, final byte[] data, Session dbSession) throws DatabaseException, IOException, SQLException { log.debug("import({}, {}, {}, {}, {})", new Object[]{userId, request, response, data, dbSession}); dbSession.doWork(new Work() { @Override public void execute(Connection con) throws SQLException { Statement stmt = con.createStatement(); InputStreamReader is = new InputStreamReader(new ByteArrayInputStream(data)); BufferedReader br = new BufferedReader(is); String query; try { while ((query = br.readLine()) != null) { stmt.executeUpdate(query); } } catch (IOException e) { throw new SQLException(e.getMessage(), e); } LegacyDAO.close(stmt); } }); log.debug("import: void"); }
/** * Execute report */ private static void executeDatabase(Session dbSession, final ByteArrayOutputStream baos, final JasperReport jr, final Map<String, Object> params, final int format) { dbSession.doWork(new Work() { @Override public void execute(Connection con) throws SQLException { try { ReportUtils.generateReport(baos, jr, params, format, con); } catch (JRException e) { throw new SQLException(e.getMessage(), e); } } }); }