Hibernate 5. Generate SQL DDL into file

前端 未结 4 2096
执念已碎
执念已碎 2021-02-06 10:07

I tried using this class:

Hibernate/JPA: Check generated sql before updating DB Schema (like .NET EF migrations)

I have the following code:

pack         


        
4条回答
  •  忘了有多久
    2021-02-06 10:39

    Apparently the Configuration class can not be used. We must use the MetadataSources class to add the annotated classes.

    private void generate(Dialect dialect, String directory, String[] packagesName) throws Exception {
    
        MetadataSources metadata = new MetadataSources(
                new StandardServiceRegistryBuilder()
                        .applySetting("hibernate.dialect", dialect.getDialectClass())
                        .build());
    
        for (String packageName : packagesName) {
            log.info("packageName: " + packageName);
            for (Class clazz : getClasses(packageName)) {
                log.info("Class: " + clazz);
                metadata.addAnnotatedClass(clazz);
            }
        }
    
        SchemaExport export = new SchemaExport(
                (MetadataImplementor) metadata.buildMetadata()
        );
    
        export.setDelimiter(";");
        export.setOutputFile(directory + "ddl_" + dialect.name().toLowerCase() + ".sql");
        export.setFormat(true);
        export.execute(true, false, false, false);
    }
    

提交回复
热议问题