Hibernate 5. Generate SQL DDL into file

前端 未结 4 2093
执念已碎
执念已碎 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:50

    The solution of felix don't work anymore on hibernate 5.2 here is a version which is compatible

    private void generate(Class dialect, String directory, String... packagesName) throws Exception {
    
        MetadataSources metadata = new MetadataSources(
                new StandardServiceRegistryBuilder()
                        .applySetting("hibernate.dialect", dialect.getName())
                        .build());
    
        for (String packageName : packagesName) {
            LOG.info("packageName: " + packageName);
            for (Class clazz : getClasses(packageName)) {
                LOG.info("Class: " + clazz);
                metadata.addAnnotatedClass(clazz);
            }
        }
    
        MetadataImplementor metadataImplementor = (MetadataImplementor) metadata.buildMetadata();
        SchemaExport export = new SchemaExport();
    
        export.setDelimiter(";");
        String filename = directory + "ddl_" + dialect.getSimpleName().toLowerCase() + ".sql";
        export.setOutputFile(filename);
        export.setFormat(true);
    
        //can change the output here
        EnumSet enumSet = EnumSet.of(TargetType.STDOUT);
        export.execute(enumSet, SchemaExport.Action.CREATE, metadataImplementor);
    }
    

提交回复
热议问题