Java Code Examples for org.hibernate.jdbc.Work

The following are top voted examples for showing how to use org.hibernate.jdbc.Work. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: query-search   File: BaseJpaTest.java   Source Code and License 7 votes vote down vote up
@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");
			}
		}
	});
}
 
Example 2
Project: opencron   File: HibernateDao.java   Source Code and License 6 votes vote down vote up
@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();
        }
    });
}
 
Example 3
Project: Equella   File: HibernateMigrationHelper.java   Source Code and License 6 votes vote down vote up
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];
}
 
Example 4
Project: quartzdesk-executor   File: DatabaseSchemaDao.java   Source Code and License 6 votes vote down vote up
/**
 * 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 );
    }
  } );
}
 
Example 5
Project: document-management-system   File: DatabaseQueryServlet.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Project: testcontainers-examples   File: DockerDatabaseTestUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
         }
      }
   });
}
 
Example 7
Project: testcontainers-examples   File: DockerDatabaseTestUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
         }
      }
   });
}
 
Example 8
Project: testcontainers-examples   File: DockerDatabaseTestUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
         }
      }

   });
}
 
Example 9
Project: testcontainers-examples   File: DockerDatabaseTestUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
         }
      }
   });
}
 
Example 10
Project: testcontainers-examples   File: DockerDatabaseTestUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
         }
      }
   });
}
 
Example 11
Project: testcontainers-examples   File: DockerDatabaseTestUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
         }
      }

   });
}
 
Example 12
Project: bamboobsc   File: HibernateExtendedJpaDialect.java   Source Code and License 6 votes vote down vote up
@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());
 }
 
Example 13
Project: owsi-core-parent   File: TestMetaModel.java   Source Code and License 6 votes vote down vote up
/**
 * <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());
		}
	});
}
 
Example 14
Project: openyu-commons   File: HibernateCfgTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 15
Project: openyu-commons   File: CommonDaoImplWithoutSpringTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 16
Project: openyu-commons   File: CommonBeanAdapterTest.java   Source Code and License 6 votes vote down vote up
@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());
		}
	});
}
 
Example 17
Project: welshare   File: HibernateExtendedJpaDialect.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 18
Project: snakerflow   File: Hibernate4Access.java   Source Code and License 6 votes vote down vote up
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);
            }
        }
    });
}
 
Example 19
Project: spring4probe   File: JPAAssertions.java   Source Code and License 6 votes vote down vote up
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);
  }
}
 
Example 20
Project: spring4probe   File: JPAAssertions.java   Source Code and License 6 votes vote down vote up
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);
  }
}
 
Example 21
Project: sigmah   File: SQLDialectProvider.java   Source Code and License 6 votes vote down vote up
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();
			}
		}
	});
}
 
Example 22
Project: sigmah   File: SiteTableHibernateDAO.java   Source Code and License 6 votes vote down vote up
/**
 * {@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;
}
 
Example 23
Project: manydesigns.cn   File: DbUtils4Its.java   Source Code and License 6 votes vote down vote up
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();
					}
				}
			}
		});

	}
 
Example 24
Project: manydesigns.cn   File: QueryUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 25
Project: manydesigns.cn   File: DbUtils.java   Source Code and License 6 votes vote down vote up
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();
				}
			}
		}
	});

}
 
Example 26
Project: openyu-mix   File: HibernateCfgTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 27
Project: hibernate-master-class   File: AbstractPooledSequenceIdentifierTest.java   Source Code and License 6 votes vote down vote up
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();
                }
            }
        }
    });
}
 
Example 28
Project: hibernate-master-class   File: TransactionIsolationExternalDataSourceConnectionProviderTest.java   Source Code and License 6 votes vote down vote up
@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();
        }
    }
}
 
Example 29
Project: hibernate-master-class   File: TransactionIsolationInternalC3P0ConnectionProviderTest.java   Source Code and License 6 votes vote down vote up
@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();
        }
    }
}
 
Example 30
Project: hibernate-master-class   File: TransactionIsolationDriverConnectionProviderTest.java   Source Code and License 6 votes vote down vote up
@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();
        }
    }
}
 
Example 31
Project: hibernate-master-class   File: TransactionIsolationExternalDataSourceExternalconfgiurationConnectionProviderTest.java   Source Code and License 6 votes vote down vote up
@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();
        }
    }
}
 
Example 32
Project: opencron   File: HibernateDao.java   Source Code and License 5 votes vote down vote up
@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();
        }
    });
}
 
Example 33
Project: Equella   File: HibernateMigrationHelper.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 34
Project: Equella   File: ConvertNtextDatabaseMigration.java   Source Code and License 5 votes vote down vote up
@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];
}
 
Example 35
Project: Equella   File: ConvertVarcharDatabaseMigration.java   Source Code and License 5 votes vote down vote up
@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];
}
 
Example 36
Project: lams   File: SessionImpl.java   Source Code and License 5 votes vote down vote up
@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 );
}
 
Example 37
Project: webpedidos   File: ExecutorRelatorioHibernate.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 38
Project: spring-boot   File: CustomHibernateJpaDialect.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 39
Project: document-management-system   File: MimeTypeServlet.java   Source Code and License 5 votes vote down vote up
/**
 * 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");
}
 
Example 40
Project: document-management-system   File: ReportUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
			}
		}
	});
}
 
Example 41
Project: springJpaKata   File: CustomHibernateJpaDialect.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 42
Project: Portofino   File: QueryUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported
 * by {@link PreparedStatement}.
 * @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 List<Object[]> runSql(Session session, final String queryString, final Object[] parameters) {
    final List<Object[]> result = new ArrayList<Object[]>();

    try {
        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                PreparedStatement stmt = connection.prepareStatement(queryString);
                try {
                    for (int i = 0; i < parameters.length; i++) {
                        stmt.setObject(i + 1, parameters[i]);
                    }
                    ResultSet rs = stmt.executeQuery();
                    ResultSetMetaData md = rs.getMetaData();
                    int cc = md.getColumnCount();
                    while(rs.next()) {
                        Object[] current = new Object[cc];
                        for(int i = 0; i < cc; i++) {
                            current[i] = rs.getObject(i + 1);
                        }
                        result.add(current);
                    }
                } finally {
                    stmt.close(); //Chiude anche il result set
                }
            }
        });
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        session.beginTransaction();
        throw e;
    }

    return result;
}
 
Example 43
Project: pedal-dialect   File: HibernateProviderAccessSpiImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void run(EntityManager entityManager, final Consumer<Connection> work) {
    Session session = entityManager.unwrap(Session.class);
    session.doWork(new Work() {

        @Override
        public void execute(Connection connection) throws SQLException {
            work.accept(connection);
        }
    });
}
 
Example 44
Project: openyu-commons   File: ApplicationContextDatabaseLogTest.java   Source Code and License 5 votes vote down vote up
@Test
public void logSessionFactory() throws Exception {
	SessionFactory bean = (SessionFactory) applicationContext.getBean("logSessionFactory");
	System.out.println(bean);
	assertNotNull(bean);
	//
	Session session = bean.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());
		}
	});
}
 
Example 45
Project: openyu-commons   File: ApplicationContextDatabaseTest.java   Source Code and License 5 votes vote down vote up
@Test
public void commonSessionFactory() throws Exception {
	SessionFactory bean = (SessionFactory) applicationContext.getBean("commonSessionFactory");
	System.out.println(bean);
	assertNotNull(bean);
	//
	Session session = bean.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());
		}
	});
}
 
Example 46
Project: pedal-dialect   File: HibernateProviderAccessSpiImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void run(EntityManager entityManager, final Consumer<Connection> work) {
    Session session = entityManager.unwrap(Session.class);
    session.doWork(new Work() {

        @Override
        public void execute(Connection connection) throws SQLException {
            work.accept(connection);
        }
    });
}
 
Example 47
Project: sigmah   File: SiteTableHibernateDAO.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public int queryCount(final User user, final Filter filter) {
	final int result[] = new int[1];
	final Session session = AbstractDAO.getSession(em());
	session.doWork(new Work() {

		@Override
		public void execute(Connection connection) throws SQLException {
			SqlSiteTableDAO dao = new SqlSiteTableDAO(connection, dialect);
			result[0] = dao.queryCount(user, filter);
		}
	});
	return result[0];
}
 
Example 48
Project: sigmah   File: SiteTableHibernateDAO.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public int queryPageNumber(final User user, final Filter filter, final List<SiteOrder> orderings, final int pageSize, final int siteId) {
	final int result[] = new int[1];
	final Session session = AbstractDAO.getSession(em());
	session.doWork(new Work() {

		@Override
		public void execute(Connection connection) throws SQLException {
			SqlSiteTableDAO dao = new SqlSiteTableDAO(connection, dialect);
			result[0] = dao.queryPageNumber(user, filter, orderings, pageSize, siteId);
		}
	});
	return result[0];
}
 
Example 49
Project: sigmah   File: GetIndicatorsHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Find the requested indicators in a transaction.
 *
 * The transaction is required by IndicatorDAO.
 * 
 * @param entityManager An Hibernate entity manager.
 * @param indicatorDAO A new indicator DAO, dedicated for this use.
 * @param userDatabaseId Identifier of the database to query.
 * @throws HibernateException 
 */
@Transactional
protected void findIndicators(final HibernateEntityManager entityManager, final IndicatorDAO indicatorDAO, final int userDatabaseId) throws HibernateException {
	entityManager.getSession().doWork(new Work() {
		
		@Override
		public void execute(Connection connection) throws SQLException {
			indicatorDAO.queryIndicatorGroups(connection, userDatabaseId);
			indicatorDAO.queryIndicatorsByDatabaseWithCurrentValues(connection, userDatabaseId);
		}
	});
}
 
Example 50
Project: manydesigns.cn   File: QueryUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Runs a SQL query against a session. The query is processed with an {@link OgnlSqlFormat}, so it can access values
 * from the OGNL context.<br>
 * INSERT UPDATE DELETE DROP CREATE ALTER TRUNCATE RENAME hongliangpan add
 * 
 * @param session the session
 * @param sql the query string
 * @return the results of the query as an Object[] (an array cell per column)
 */
public static int runSqlDml(Session session, String sql) {
	OgnlSqlFormat sqlFormat = OgnlSqlFormat.create(sql);
	final String queryString = sqlFormat.getFormatString();
	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;
}
 
Example 51
Project: openyu-mix   File: ApplicationContextDatabaseLogTest.java   Source Code and License 5 votes vote down vote up
@Test
public void logSessionFactory() throws Exception {
	SessionFactory bean = (SessionFactory) applicationContext.getBean("logSessionFactory");
	System.out.println(bean);
	assertNotNull(bean);
	//
	Session session = bean.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());
		}
	});
}
 
Example 52
Project: openyu-mix   File: ApplicationContextDatabaseTest.java   Source Code and License 5 votes vote down vote up
@Test
public void commonSessionFactory() throws Exception {
	SessionFactory bean = (SessionFactory) applicationContext.getBean("commonSessionFactory");
	System.out.println(bean);
	assertNotNull(bean);
	//
	Session session = bean.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());
		}
	});
}
 
Example 53
Project: open-cyclos   File: BaseDAOImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Runs something directly in the database connection using a {@link JDBCCallback}
 */
protected void runNative(final JDBCCallback callback) {
    getSession().doWork(new Work() {
        @Override
        public void execute(final Connection connection) throws SQLException {
            callback.execute(new JDBCWrapper(connection));
        }
    });
    // As there is no way to know whether the native execution performed writes, assume yes
    CurrentTransactionData.setWrite();
}
 
Example 54
Project: dcp-api   File: JpaHibernateContentPersistenceServiceTest.java   Source Code and License 5 votes vote down vote up
private void assertTableContent(final JpaHibernateContentPersistenceService tested, final String dcpContentType,
		final String id, final Date expectedUpdated) {
	tested.doDatabaseWork(new Work() {

		@Override
		public void execute(Connection connection) throws SQLException {
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				ps = connection.prepareStatement("select dcp_content_type, updated from "
						+ tested.getTableName(dcpContentType) + " where id = ?");
				ps.setString(1, id);
				rs = ps.executeQuery();
				Assert.assertTrue(rs.next());
				Assert.assertEquals(dcpContentType, rs.getString(1));
				Timestamp actualTimestamp = rs.getTimestamp(2);
				if (expectedUpdated != null) {
					Assert.assertEquals(new Timestamp(expectedUpdated.getTime()), actualTimestamp);
				} else {
					Assert.assertNotNull(actualTimestamp);
				}

			} finally {
				JpaHibernateContentPersistenceService.closeJDBCStuff(ps, rs);
			}
		}

	});
}
 
Example 55
Project: IBE-Secure-Message   File: IDRequestDAOHibernateImpl.java   Source Code and License 5 votes vote down vote up
public void requestHandled(Map<String, Integer> results) {
	Session session = factory.openSession();
	final Map<String, Integer> results0 = results;
	session.doWork(new Work() {
		@Override
		public void execute(Connection connection) throws SQLException {
			requestHandledDBMSSpecImpl(connection, results0);
		}
	});
	if (session.isConnected())
		session.disconnect();
}
 
Example 56
Project: vladmihalcea.wordpress.com   File: StoreServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Transactional(isolation = Isolation.SERIALIZABLE)
public void purchase(Long productId) {
    Product product = entityManager.find(Product.class, 1L);
    Session session = (Session) entityManager.getDelegate();
    session.doWork(new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
            LOGGER.debug("Transaction isolation level is {}", Environment.isolationLevelToString(connection.getTransactionIsolation()));
        }
    });
    product.setQuantity(product.getQuantity() - 1);
}
 
Example 57
Project: Equella   File: HibernateMigrationHelper.java   Source Code and License 4 votes vote down vote up
public Map<Set<String>, String> getExistingIndexes(final Table table, Session session)
{
	final Map<String, Set<String>> indexMap = new HashMap<String, Set<String>>();

	// Query existing index
	session.doWork(new Work()
	{
		@Override
		public void execute(Connection connection) throws SQLException
		{
			ResultSet colresult = connection.getMetaData().getIndexInfo(getDefaultCatalog(),
				extDialect.getNameForMetadataQuery(getDefaultSchema(), false),
				extDialect.getNameForMetadataQuery(table.getName(), table.isQuoted()), false, false);
			try
			{
				while( colresult.next() )
				{
					String indexName = colresult.getString("INDEX_NAME");
					String columnName = colresult.getString("COLUMN_NAME");
					if( columnName != null )
					{
						columnName = columnName.toLowerCase();
						Set<String> cols = indexMap.get(indexName);
						if( cols == null )
						{
							cols = new HashSet<String>();
							indexMap.put(indexName, cols);
						}
						cols.add(columnName);
					}
				}
			}
			finally
			{
				colresult.close();
			}
		}
	});
	// Change from (index -> cols) to (cols -> index)
	Map<Set<String>, String> revIndexMap = new HashMap<Set<String>, String>();
	for( Map.Entry<String, Set<String>> entry : indexMap.entrySet() )
	{
		revIndexMap.put(entry.getValue(), entry.getKey());
	}
	return revIndexMap;
}
 
Example 58
Project: Equella   File: ConvertNtextDatabaseMigration.java   Source Code and License 4 votes vote down vote up
@Override
protected void executeDataMigration(final HibernateMigrationHelper helper, final MigrationResult result,
	Session session)
{
	final Dialect dialect = helper.getFactory().getDialect();

	if( dialect instanceof SQLServerDialect )
	{
		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"});
				final List<String> tableNames = Lists.newArrayList();
				try
				{
					while( tableSet.next() )
					{
						tableNames.add(tableSet.getString("TABLE_NAME"));
					}
				}
				finally
				{
					tableSet.close();
				}

				for( String tableName : tableNames )
				{
					final List<ColMeta> ntextCols = Lists.newArrayList();
					final ResultSet columnSet = metaData.getColumns(defaultCatalog, defaultSchema, tableName, null);

					try
					{
						while( columnSet.next() )
						{
							final String colName = columnSet.getString("COLUMN_NAME");
							final String colDbType = columnSet.getString("TYPE_NAME");
							if( colDbType.equalsIgnoreCase("ntext") )
							{
								LOGGER.info("ntext column found: " + tableName + "." + colName);

								final int nullable = columnSet.getInt("NULLABLE");
								final ColMeta colMeta = new ColMeta();
								colMeta.nullable = (nullable != DatabaseMetaData.columnNoNulls);
								colMeta.name = colName;
								ntextCols.add(colMeta);
							}
						}
					}
					finally
					{
						columnSet.close();
					}

					for( ColMeta ntextCol : ntextCols )
					{
						final String sql = "ALTER TABLE " + Table.qualify(defaultCatalog, defaultSchema, tableName)
							+ " ALTER COLUMN " + ntextCol.name + " nvarchar(max)"
							+ (ntextCol.nullable ? "" : " NOT") + " NULL";
						final PreparedStatement s = connection.prepareStatement(sql);
						s.execute();
					}

					// We don't seem to need to update
					// http://stackoverflow.com/questions/4708463/converting-ntext-to-nvcharmaxmax-getting-around-size-limitation
					result.incrementStatus();
				}
			}
		});
	}
}
 
Example 59
Project: Equella   File: ConvertVarcharDatabaseMigration.java   Source Code and License 4 votes vote down vote up
@Override
protected void executeDataMigration(final HibernateMigrationHelper helper, final MigrationResult result,
	Session session)
{
	final Dialect dialect = helper.getFactory().getDialect();

	if( dialect instanceof SQLServerDialect )
	{
		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"});
				final List<String> tableNames = Lists.newArrayList();
				try
				{
					while( tableSet.next() )
					{
						tableNames.add(tableSet.getString("TABLE_NAME"));
					}
				}
				finally
				{
					tableSet.close();
				}

				for( String tableName : tableNames )
				{
					final List<ColMeta> ntextCols = Lists.newArrayList();
					final ResultSet columnSet = metaData.getColumns(defaultCatalog, defaultSchema, tableName, null);

					try
					{
						while( columnSet.next() )
						{
							final String colName = columnSet.getString("COLUMN_NAME");
							final String colDbType = columnSet.getString("TYPE_NAME");
							if( colDbType.equalsIgnoreCase("varchar") || colDbType.equalsIgnoreCase("text") )
							{
								LOGGER.info("varchar column found: " + tableName + "." + colName);

								final int nullable = columnSet.getInt("NULLABLE");
								final ColMeta colMeta = new ColMeta();
								colMeta.size = columnSet.getInt("COLUMN_SIZE");
								colMeta.nullable = (nullable != DatabaseMetaData.columnNoNulls);
								colMeta.name = colName;
								ntextCols.add(colMeta);
							}
						}
					}
					finally
					{
						columnSet.close();
					}

					for( ColMeta ntextCol : ntextCols )
					{
						String sizeStr = ntextCol.size == Integer.MAX_VALUE ? "max"
							: Integer.toString(ntextCol.size);
						final String sql = "ALTER TABLE " + Table.qualify(defaultCatalog, defaultSchema, tableName)
							+ " ALTER COLUMN " + ntextCol.name + " nvarchar(" + sizeStr + ")"
							+ (ntextCol.nullable ? "" : " NOT") + " NULL";
						final PreparedStatement s = connection.prepareStatement(sql);
						s.execute();
					}

					result.incrementStatus();
				}
			}
		});
	}
}
 
Example 60
Project: lams   File: SessionDelegatorBaseImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void doWork(Work work) throws HibernateException {
	session.doWork( work );
}