Java 类org.hibernate.tool.hbm2ddl.SchemaUpdate 实例源码
项目:cacheonix-core
文件:MigrationTest.java
public void testSimpleColumnAddition() {
String resource1 = "org/hibernate/test/schemaupdate/1_Version.hbm.xml";
String resource2 = "org/hibernate/test/schemaupdate/2_Version.hbm.xml";
Configuration v1cfg = new Configuration();
v1cfg.addResource( resource1 );
new SchemaExport( v1cfg ).execute( false, true, true, false );
SchemaUpdate v1schemaUpdate = new SchemaUpdate( v1cfg );
v1schemaUpdate.execute( true, true );
assertEquals( 0, v1schemaUpdate.getExceptions().size() );
Configuration v2cfg = new Configuration();
v2cfg.addResource( resource2 );
SchemaUpdate v2schemaUpdate = new SchemaUpdate( v2cfg );
v2schemaUpdate.execute( true, true );
assertEquals( 0, v2schemaUpdate.getExceptions().size() );
}
项目:Lucee4
文件:HibernateSessionFactory.java
private static void schemaExport(Log log,Configuration configuration, DatasourceConnection dc, SessionFactoryData data) throws PageException, SQLException, IOException {
ORMConfiguration ormConf = data.getORMConfiguration();
if(ORMConfiguration.DBCREATE_NONE==ormConf.getDbCreate()) {
return;
}
else if(ORMConfiguration.DBCREATE_DROP_CREATE==ormConf.getDbCreate()) {
SchemaExport export = new SchemaExport(configuration);
export.setHaltOnError(true);
export.execute(false,true,false,false);
printError(log,data,export.getExceptions(),false);
executeSQLScript(ormConf,dc);
}
else if(ORMConfiguration.DBCREATE_UPDATE==ormConf.getDbCreate()) {
SchemaUpdate update = new SchemaUpdate(configuration);
update.setHaltOnError(true);
update.execute(false, true);
printError(log,data,update.getExceptions(),false);
}
}
项目:yawl
文件:YPersistenceManager.java
protected SessionFactory initialise(boolean journalising) throws YPersistenceException {
Configuration cfg;
// Create the Hibernate config, check and create database if required,
// and generally set things up .....
if (journalising) {
try {
cfg = new Configuration();
for (Class persistedClass : persistedClasses) {
cfg.addClass(persistedClass);
}
factory = cfg.buildSessionFactory();
new SchemaUpdate(cfg).execute(false, true);
setEnabled(true);
} catch (Exception e) {
e.printStackTrace();
logger.fatal("Failure initialising persistence layer", e);
throw new YPersistenceException("Failure initialising persistence layer", e);
}
}
return factory;
}
项目:gamedev-server
文件:HibernateUtil.java
/**
* Initializes the hibernate system.
*/
public static void init() {
logger.debug("Initializing hibernate...");
Configuration configuration = new Configuration().configure();
logger.debug("Performing schema update");
new SchemaUpdate(configuration).execute(true, true);
ServiceRegistry serviceRegistry =
new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
logger.debug("Hibernate initialized");
}
项目:zeprs
文件:DynasiteSourceGenerator.java
public void updateSchema() {
/**
* Loads the Hibernate configuration information, sets up
* the database and the Hibernate session factory.
*/
System.out.println("initialization");
try {
Configuration myConfiguration = new Configuration().configure();
// Load the *.hbm.xml files as set in the
// config, and set the dialect.
new SchemaUpdate(myConfiguration)
.execute(true, true);
} catch (Exception e) {
e.printStackTrace();
}
}
项目:finances
文件:HibernateDaoContext.java
public static void main(String[] args) {
try {
DriverService driverService = CONNECTION_CONFIG.loadDriver();
HibernateDaoContext context = new HibernateDaoContext(driverService, ApplicationConfig.CONFIG);
// Stream.of(context.schemaCreationScript()).forEach(System.out::println);
new SchemaUpdate(context.configuration).execute(Target.SCRIPT);
} catch (Exception ex) {
ex.printStackTrace();
}
}
项目:mojito
文件:DDLGenerator.java
@Test
public void generateCreateAnUpdateDDL() throws IOException {
logger.debug("Generate create and update DDL");
EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl) lcemfb.getNativeEntityManagerFactory();
SessionFactoryImpl sf = emf.getSessionFactory();
SessionFactoryServiceRegistryImpl serviceRegistry = (SessionFactoryServiceRegistryImpl) sf.getServiceRegistry();
Configuration cfg = null;
try {
Field field = SessionFactoryServiceRegistryImpl.class.getDeclaredField("configuration");
field.setAccessible(true);
cfg = (Configuration) field.get(serviceRegistry);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
Files.createDirectories(Paths.get("target/db/migration/"));
SchemaUpdate update = new SchemaUpdate(serviceRegistry, cfg);
update.setDelimiter(";");
update.setOutputFile("target/db/migration/Vx__yy_zz.sql");
update.execute(false, false);
SchemaExport export = new SchemaExport(serviceRegistry, cfg);
export.setDelimiter(";");
export.setOutputFile("target/db/migration/create.sql");
export.execute(false, false, false, true);
}
项目:cacheonix-core
文件:TestSchemaTools.java
public void testSchemaTools() throws Exception{
// database schema have been created thanks to the setUp method
// we have 2 schemas SA et SB, SB must be set as the default schema
// used by hibernate hibernate.default_schema SB
SchemaExport se = new SchemaExport(getCfg());
se.create(true,true);
// here we modify the generated table in order to test SchemaUpdate
Session session = openSession();
Connection conn = session.connection();
Statement stat = conn.createStatement();
stat.execute("ALTER TABLE \"SB\".\"Team\" DROP COLUMN name ");
// update schema
SchemaUpdate su = new SchemaUpdate(getCfg());
su.execute(true,true);
// we can run schema validation. Note that in the setUp method a *wrong* table
// has been created with different column names
// if schema validator chooses the bad db schema, then the testcase will fail (exception)
SchemaValidator sv = new SchemaValidator(getCfg());
sv.validate();
// it's time to clean our database
se.drop(true,true);
// then the schemas and false table.
stat.execute("DROP TABLE \"SA\".\"Team\" ");
stat.execute(" DROP SCHEMA sa ");
stat.execute("DROP SCHEMA sb ");
stat.close();
session.close();
}
项目:cacheonix-core
文件:TestSchemaTools.java
public void testSchemaToolsNonQuote() throws Exception{
// database schema have been created thanks to the setUp method
// we have 2 schemas SA et SB, SB must be set as the default schema
// used by hibernate hibernate.default_schema SB
SchemaExport se = new SchemaExport(getCfg());
se.create(true,true);
// here we modify the generated table in order to test SchemaUpdate
Session session = openSession();
Connection conn = session.connection();
Statement stat = conn.createStatement();
stat.execute("ALTER TABLE \"SB\".\"TEAM\" DROP COLUMN xname ");
// update schema
SchemaUpdate su = new SchemaUpdate(getCfg());
su.execute(true,true);
// we can run schema validation. Note that in the setUp method a *wrong* table
// has been created with different column names
// if schema validator chooses the bad db schema, then the testcase will fail (exception)
SchemaValidator sv = new SchemaValidator(getCfg());
sv.validate();
// it's time to clean our database
se.drop(true,true);
// then the schemas and false table.
stat.execute("DROP TABLE \"SA\".\"Team\" ");
stat.execute(" DROP SCHEMA sa ");
stat.execute("DROP SCHEMA sb ");
stat.close();
session.close();
}
项目:yawl
文件:HibernateEngine.java
public void configureSession(Properties props, List<Class> classes) {
Configuration cfg = new Configuration();
cfg.setProperties(props);
if (classes != null) {
for (Class className : classes) {
cfg.addClass(className);
}
}
_factory = cfg.buildSessionFactory(); // get a session context
// check tables exist and are of a matching format to the persisted objects
new SchemaUpdate(cfg).execute(false, true);
}
项目:yawl
文件:HibernateEngine.java
/** initialises hibernate and the required tables */
private void initialise(Set<Class> classes, Properties props) throws HibernateException {
try {
Configuration _cfg = new Configuration();
// if props supplied, use them instead of hibernate.properties
if (props != null) {
_cfg.setProperties(props);
}
// add each persisted class to config
for (Class persistedClass : classes) {
_cfg.addClass(persistedClass);
}
// get a session context
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(_cfg.getProperties()).build();
_factory = _cfg.buildSessionFactory(serviceRegistry);
// check tables exist and are of a matching format to the persisted objects
new SchemaUpdate(_cfg).execute(false, true);
}
catch (MappingException me) {
_log.error("Could not initialise database connection.", me);
}
}
项目:olat
文件:DatabaseSetup.java
/**
* Generates alter database DDL and EXECUTES it.
*/
private static void updateDatabaseDDL() {
boolean printToOut = true; // write to System.out
boolean updateDatabase = false;
try {
new SchemaUpdate(cf).execute(printToOut, updateDatabase);
} catch (Exception e) {
log.error("DDL export to file failed: Reason: ", e);
}
}
项目:olat
文件:DatabaseSetup.java
/**
* Generates alter database DDL and EXECUTES it.
*/
private static void updateDatabaseDDL() {
boolean printToOut = true; // write to System.out
boolean updateDatabase = false;
try {
new SchemaUpdate(cf).execute(printToOut, updateDatabase);
} catch (Exception e) {
log.error("DDL export to file failed: Reason: ", e);
}
}
项目:windup-rulesets
文件:SchemaDDLGenerator.java
public static void execute(Dialect dialect, Class<?>... classes) {
Configuration configuration = new Configuration();
SchemaExport schemaExport = new SchemaExport(configuration);
SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
try {
new SchemaValidator(configuration).validate();
}
catch (Exception e) {
logger.error("Failed create the table: " + e.getMessage());
}
}
项目:projectforge-webapp
文件:SchemaExport.java
/** Updates the current DB-Schema with the schema defined by the hbm.xml files.
*
* @param script Print the DDL to the console.
* @param export
*/
public void updateSchema(Configuration cfg, boolean script, boolean export) {
try {
SchemaUpdate exp = new SchemaUpdate(cfg);
exp.execute(script, export);
} catch (HibernateException ex) {
log.fatal("Cant't update database schema: " + ex.getMessage(), ex);
return;
}
}
项目:openhds-server
文件:AnnotationSchemaUpdate.java
public static void main(String[] args) {
File currentDirectory = new File("");
File config = new File(currentDirectory.getAbsolutePath() + File.separatorChar + RESOURCES_PATH + "hibernate.cfg.xml");
Configuration cfg = new AnnotationConfiguration();
cfg.configure(config);
SchemaUpdate se = new SchemaUpdate(cfg);
se.setOutputFile(RESOURCES_PATH + "openhds-schema-update.sql");
se.execute(false, false);
}
项目:GridSphere
文件:CreateDatabase.java
private void updateDatabase(Configuration cfg) throws PersistenceManagerException {
try {
new SchemaUpdate(cfg).execute(false, true);
} catch (HibernateException e) {
log.error("DB Error: " + UPDATE_ERROR + " !", e);
throw new PersistenceManagerException("DB Error: " + UPDATE_ERROR + " ! " + e.getMessage());
}
}
项目:engerek
文件:OrgClosureManager.java
private boolean autoUpdateClosureTableStructure() {
if (baseHelper.getConfiguration().isSkipOrgClosureStructureCheck()) {
LOGGER.debug("Skipping org closure structure check.");
return false;
}
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;
}
项目:omr
文件:MySchemaUpdate.java
public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration
.configure("/br/com/dlp/jazzqa/hibernateLocal.cfg.xml");
SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
schemaUpdate.execute(true, true);
} catch (HibernateException e) {
e.printStackTrace();
}
}
项目:mamute
文件:MamuteDatabaseConfiguration.java
public SchemaUpdate getSchemaUpdate() {
return new SchemaUpdate(cfg);
}
项目:billiards
文件:MakeTable.java
public static void updateTable(String[] args) {
Configuration config = new Configuration().configure();
SchemaUpdate su = new SchemaUpdate(config);
su.execute(true, true);
}