private void generateDDL() throws Exception { final MetadataImplementor md = createMetaData(); final SchemaExport export = new SchemaExport(md); // drop { export.setDelimiter(";"); export.setOutputFile(getRefPath() + "/db-drop.sql"); export.setFormat(true); export.execute(true, false, true, false); } // create { export.setDelimiter(";"); export.setOutputFile(getRefPath() + "/db-create.sql"); export.setFormat(true); export.execute(true, false, false, true); } }
protected void applyConstraints(Metadata metadata) { File tempFile = null; try { tempFile = File.createTempFile("schema", ".sql"); new SchemaExport().setOutputFile(tempFile.getAbsolutePath()) .setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata); List<String> sqls = new ArrayList<>(); for (String sql: FileUtils.readLines(tempFile)) { if (isApplyingConstraints(sql)) { sqls.add(sql); } } execute(sqls, true); } catch (IOException e) { throw new RuntimeException(e); } finally { if (tempFile != null) tempFile.delete(); } }
protected void createTables(Metadata metadata) { File tempFile = null; try { tempFile = File.createTempFile("schema", ".sql"); new SchemaExport().setOutputFile(tempFile.getAbsolutePath()) .setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata); List<String> sqls = new ArrayList<>(); for (String sql: FileUtils.readLines(tempFile)) { if (shouldInclude(sql) && !isApplyingConstraints(sql)) sqls.add(sql); } execute(sqls, true); } catch (IOException e) { throw new RuntimeException(e); } finally { if (tempFile != null) FileUtils.deleteFile(tempFile); } }
protected void dropConstraints(Metadata metadata) { File tempFile = null; try { tempFile = File.createTempFile("schema", ".sql"); new SchemaExport().setOutputFile(tempFile.getAbsolutePath()) .setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata); List<String> sqls = new ArrayList<>(); for (String sql: FileUtils.readLines(tempFile)) { if (isDroppingConstraints(sql)) sqls.add(sql); } execute(sqls, false); } catch (IOException e) { throw new RuntimeException(e); } finally { if (tempFile != null) tempFile.delete(); } }
protected void cleanDatabase(Metadata metadata) { File tempFile = null; try { tempFile = File.createTempFile("schema", ".sql"); new SchemaExport().setOutputFile(tempFile.getAbsolutePath()) .setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata); List<String> sqls = new ArrayList<>(); for (String sql: FileUtils.readLines(tempFile)) { sqls.add(sql); } execute(sqls, false); } catch (IOException e) { throw new RuntimeException(e); } finally { if (tempFile != null) tempFile.delete(); } }
private void outputDdl(String packageName, String dialect, String fileName) { LocalSessionFactoryBean sfBean = sfBean(packageName, dialect); StandardServiceRegistry serviceRegistry = sfBean.getConfiguration().getStandardServiceRegistryBuilder().build(); try { String outputFile = OutputRoot + fileName; Files.deleteIfExists(Paths.get(outputFile)); MetadataImplementor metadata = metadata(sfBean, serviceRegistry); SchemaExport export = new SchemaExport(); export.setDelimiter(";"); export.setFormat(FormatSql); export.setOutputFile(outputFile); export.create(EnumSet.of(TargetType.SCRIPT), metadata); } catch (Exception e) { throw new InvocationException(e); } finally { StandardServiceRegistryBuilder.destroy( serviceRegistry ); } }
/** * Generate database schema and initial data for a defined dialect */ public static void generateDatabase(String dialect) throws IOException { // Configure Hibernate log.info("Exporting Database Schema..."); String dbSchema = EnvironmentDetector.getUserHome() + "/schema.sql"; Configuration cfg = getConfiguration().configure(); cfg.setProperty("hibernate.dialect", dialect); SchemaExport se = new SchemaExport(cfg); se.setOutputFile(dbSchema); se.setDelimiter(";"); se.setFormat(false); se.create(false, false); log.info("Database Schema exported to {}", dbSchema); String initialData = new File("").getAbsolutePath() + "/src/main/resources/default.sql"; log.info("Exporting Initial Data from '{}'...", initialData); String initData = EnvironmentDetector.getUserHome() + "/data.sql"; FileInputStream fis = new FileInputStream(initialData); String ret = DatabaseDialectAdapter.dialectAdapter(fis, dialect); FileWriter fw = new FileWriter(initData); IOUtils.write(ret, fw); fw.flush(); fw.close(); log.info("Initial Data exported to {}", initData); }
/** * Only for testing purposes */ public static void main(String[] args) throws Exception { log.info("Generate database schema & initial data"); HibernateUtil.generateDatabase("org.hibernate.dialect.Oracle10gDialect"); Configuration cfg = new Configuration(); // Add annotated beans cfg.addAnnotatedClass(NodeFolder.class); // Configure Hibernate cfg.setProperty("hibernate.dialect", Config.HIBERNATE_DIALECT); cfg.setProperty("hibernate.hbm2ddl.auto", "create"); SchemaExport se = new SchemaExport(cfg); se.setOutputFile("/home/pavila/export.sql"); se.setDelimiter(";"); se.setFormat(false); se.create(false, false); }
private void createSQLSchema(String fileName, String dialect) throws Exception { org.hibernate.cfg.Configuration configuration = new Configuration(); configuration.setNamingStrategy(new MidPointNamingStrategy()); configuration.setProperties(sessionFactory.getHibernateProperties()); sessionFactory.getHibernateProperties().setProperty("hibernate.dialect", dialect); System.out.println("Dialect: " + sessionFactory.getHibernateProperties().getProperty("hibernate.dialect")); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.container", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.any", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.embedded", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.enums", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.id", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.other", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.type", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.audit", configuration); // addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.poc", configuration); configuration.addPackage("com.evolveum.midpoint.repo.sql.type"); SchemaExport export = new SchemaExport(configuration); export.setOutputFile(fileName); export.setDelimiter(";"); export.execute(true, false, false, true); }
protected void prepareTest() throws Exception { super.prepareTest(); Connection conn = cp.getConnection(); try { new SchemaExport( getCfg(), conn ).create( false, true ); } finally { if ( conn != null ) { try { cp.closeConnection( conn ); } catch( Throwable ignore ) { } } } }
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() ); }
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); } }
protected void dropSchema() throws ExecutionException, InterruptedException, IOException { log.info("Dropping schema!"); Configuration config = new Configuration(); Properties properties = new Properties(); properties.putAll(entityManagerFactory.getProperties()); config.setProperties(properties); entityManagerFactory.getMetamodel().getEntities() .stream() .map(EntityType::getJavaType) .forEach(config::addAnnotatedClass); EntityManagerImpl em = (EntityManagerImpl) entityManager; Session session = em.getSession(); session.doWork(connection -> new SchemaExport(config, connection).create(false, true)); entityManager.clear(); log.info("Dropped schema successfully!"); }
protected void export(Class<? extends Dialect> dialect, String app_key, Configuration configuration, boolean create, boolean drop) { Assert.notNull(dialect, "dialect is invalid [null]"); Assert.notNull(app_key, "app_key is invalid [null]"); Assert.notNull(configuration, "configuration is invalid [null]"); SchemaExport schemaExport = new SchemaExport(configuration); schemaExport.setDelimiter(";"); schemaExport.setFormat(true); if (create) { // Generate create script schemaExport.setOutputFile(String.format("target/%s_ddl_%s_create.sql", app_key, dialect.getSimpleName())); schemaExport.execute(true, false, false, true); } if (drop) { // Generate drop script schemaExport.setOutputFile(String.format("target/%s_ddl_%s_drop.sql", app_key, dialect.getSimpleName())); schemaExport.execute(true, false, true, false); } }
protected void export(Class<? extends Dialect> dialect, String app_key, MetadataSources metadata, boolean create, boolean drop) { Assert.notNull(dialect, "dialect is invalid [null]"); Assert.notNull(app_key, "app_key is invalid [null]"); Assert.notNull(metadata, "metadata is invalid [null]"); SchemaExport schemaExport = new SchemaExport((MetadataImplementor) metadata.buildMetadata()); schemaExport.setDelimiter(";"); schemaExport.setFormat(true); if (create) { // Generate create script schemaExport.setOutputFile(String.format("target/%s_ddl_%s_create.sql", app_key, dialect.getSimpleName())); schemaExport.execute(true, false, false, true); } if (drop) { // Generate drop script schemaExport.setOutputFile(String.format("target/%s_ddl_%s_drop.sql", app_key, dialect.getSimpleName())); schemaExport.execute(true, false, true, false); } }
/** * Method that actually creates the file. * * @param dbDialect to use */ private void generate(Dialect dialect) { StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(); ssrb.applySetting("hibernate.dialect", dialect.getDialectClass()); StandardServiceRegistry standardServiceRegistry = ssrb.build(); MetadataSources metadataSources = new MetadataSources(standardServiceRegistry); for (Class clzz : jpaClasses) { metadataSources.addAnnotatedClass(clzz); } Metadata metadata = metadataSources.buildMetadata(); SchemaExport export = new SchemaExport(); export.setDelimiter(";"); export.setOutputFile(dialect.name().toLowerCase() + ".ddl"); //export.execute(true, false, false, true); export.execute(EnumSet.of(TargetType.SCRIPT), Action.BOTH, metadata); }
/** * Controller method to download a ddl. */ @Deprecated @SuppressWarnings({"unchecked", "rawtypes"}) @RequestMapping(value = "ddl", method = RequestMethod.GET) public void exportDatabaseSchema(HttpServletRequest request, HttpServletResponse response, Model uiModel) { PersistenceUnitInfo persistenceUnitInfo = getEntityManagerFactory().getPersistenceUnitInfo(); Map jpaPropertyMap = getEntityManagerFactory().getJpaPropertyMap(); jpaPropertyMap.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); Configuration configuration = new Ejb3Configuration().configure(persistenceUnitInfo, jpaPropertyMap).getHibernateConfiguration(); SchemaExport schema = new SchemaExport(configuration); schema.setFormat(true); schema.setDelimiter(";"); schema.setOutputFile("/tmp/schema.sql"); schema.create(false, false); }
private void createSQLSchema(String fileName) throws Exception { org.hibernate.cfg.Configuration configuration = new Configuration(); Properties properties = new Properties(); properties.putAll(sessionFactoryBean.getJpaPropertyMap()); configuration.setProperties(properties); configuration.setNamingStrategy(new GizmoNamingStrategy()); System.out.println("Dialect: " + properties.getProperty("hibernate.dialect")); addAnnotatedClasses("sk.lazyman.gizmo.data", configuration); SchemaExport export = new SchemaExport(configuration); export.setOutputFile(fileName); export.setDelimiter(";"); export.execute(true, false, false, true); }
public static void main(String[] args) { Configuration hello =new Configuration(); Properties properties = new Properties(); properties.setProperty(Environment.DIALECT, MySQL5Dialect.class.getName()); hello.setProperties(properties); hello.addAnnotatedClass(Hello.class); hello.addAnnotatedClass(Hello1.class); SchemaExport schemaExport = new SchemaExport(hello); schemaExport.setDelimiter(";"); // schemaExport.setOutputFile(String.format("%s_%s.%s ", new Object[] {"ddl", dialect.name().toLowerCase(), "sql" })); boolean consolePrint = true; boolean exportInDatabase = false; // schemaExport.create(consolePrint, exportInDatabase); schemaExport.create(Target.SCRIPT); }
/** * @param args */ public static void main(String[] args) { // Configuration config = new AnnotationConfiguration().configure(); AnnotationConfiguration config = new AnnotationConfiguration().configure(); config.addAnnotatedClass(TUser.class) .addAnnotatedClass(TGameDetailRecord.class) .addAnnotatedClass(TMatch.class) .addAnnotatedClass(TMatchType.class) .addAnnotatedClass(TResult.class); /* config.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); new SchemaExport(cfg, connection);*/ SchemaExport se = new SchemaExport(config); se.create(true, true); }
@Test public void generateCreate() throws ClassNotFoundException { final long now = System.currentTimeMillis() - LAST_MODIFIED_PRECISION; final Configuration cfg = new Configuration(); cfg.setProperty("hibernate.hbm2ddl.auto", "create"); cfg.setProperty("hibernate.dialect", ORACLE_DIALECT); cfg.setNamingStrategy(new MyNamingStrategy()); for (final String className : findEntities()) { cfg.addAnnotatedClass(Class.forName(className)); } final SchemaExport export = new SchemaExport(cfg); export.setDelimiter(";"); export.setOutputFile(CREATE_FILE_NAME); export.execute(true, false, false, true); File file = new File(CREATE_FILE_NAME); assertThat(file.lastModified()).as("the file should be generated").isGreaterThan(now); }
public static void main(String[] args) { Ejb3Configuration ejb3Cfg = new Ejb3Configuration(); // set propeties (these were set based on the persistence.xml file) Properties props = new Properties(); props.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); ejb3Cfg.addProperties(props); ejb3Cfg.setNamingStrategy(ImprovedNamingStrategy.INSTANCE); // add annotated classes ejb3Cfg.addAnnotatedClass(EndUser.class); ejb3Cfg.addAnnotatedClass(Individual.class); ejb3Cfg.addAnnotatedClass(Location.class); ejb3Cfg.addAnnotatedClass(SocialGroup.class); ejb3Cfg.addAnnotatedClass(Visit.class); Configuration cfg = ejb3Cfg.getHibernateConfiguration(); SchemaExport se = new SchemaExport(cfg).setOutputFile(RESOURCES_PATH + "specialstudy-schema-ddl.sql"); se.execute(false, false, false, true); }
@Test public void testDbSchema() { MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder() .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect").build()); metadata.addAnnotatedClass(ConsoleEntity.class); metadata.addAnnotatedClass(GameEntity.class); metadata.addAnnotatedClass(UserEntity.class); metadata.addAnnotatedClass(RoleEntity.class); metadata.addAnnotatedClass(LibraryEntity.class); metadata.addAnnotatedClass(BorrowEntity.class); SchemaExport export = new SchemaExport((MetadataImplementor) metadata.buildMetadata()); export.create(Target.SCRIPT); }
public static void main(String[] args){ String file = "camping-db-creation.sql"; new File(file).delete(); MetadataSources metadata = new MetadataSources( new StandardServiceRegistryBuilder().configure().build()); SchemaExport export = new SchemaExport(); export.setOutputFile(file); export.setDelimiter(";"); export.setFormat(true); export.execute(EnumSet.of(TargetType.SCRIPT), SchemaExport.Action.CREATE, metadata.buildMetadata()); }
@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); }
/** * Generate schema. */ public void generateSchema() { Configuration config; try { config = this.getHibernateConfig(); final Session session = this.getHibernateSession(); final Transaction tx = session.beginTransaction(); final SchemaExport sch = new SchemaExport(config); sch.create(true, true); tx.commit(); } catch (final Exception e) { e.printStackTrace(); } }
@Test public void testSchemaExport() { ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); MetadataImplementor metadataImplementor = (MetadataImplementor) new MetadataSources(serviceRegistry).buildMetadata(); SchemaExport schemaExport = new SchemaExport(serviceRegistry, metadataImplementor); schemaExport.create(true, true); }
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(); }
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(); }
public void testFailingQuoteValidation() 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); try { SchemaValidator sv = new SchemaValidator(getCfg()); sv.validate(); fail("should fail since we mutated the current schema."); } catch(HibernateException he) { } // 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(); }