如何导出 Hibernate > 4.3 的模式

3

有很多文章介绍如何使用Hibernate以编程方式导出模式(例如[1])。

但是在Hibernate 4.3中,类org.hibernate.ejb.Ejb3Configuration被删除了,我找不到它的替代品。 如何在Hibernate版本> = 4.3中以编程方式生成ddl脚本? 由于我正在使用Spring设置实体管理器,因此我也不必再使用persitence.xml,我希望保持这种状态。

[1] http://techblog.bozho.net/?p=935


你能解决这个问题吗?如果可以,请发一下。我也遇到了类似的情况,不使用 persistence.xml。 - Himalay Majumdar
不好意思,我放弃了这个 - 但你可能可以根据@mabi的答案完成它。 - domi
4个回答

2

关于@geoand的回答,我撰写了一个独立的SchemaGenerator groovy脚本来触发SchemaExport类:

class SchemaGenerator {
static final void main(String[] args) {
    def outputPath = args[0]
    def classesDir = args[1]

    Configuration cfg = new Configuration()
    cfg.setProperty('hibernate.dialect', 'org.hibernate.dialect.PostgreSQLDialect')
    cfg.setProperty('hibernate.hbm2ddl.auto', 'create')

    addClasses(cfg, new File(classesDir), 'my.entity.package.prefix')

    SchemaExport export = new SchemaExport(cfg)
    export.outputFile = new File(outputPath)
    export.delimiter = ';'
    export.format = true

    export.execute(true, false, false, true)
}
// addClasses uses cfg.addAnnotatedClass(Class) where it grabs the Class instance
// with Class.forName(name) with name derived from iterating the file structure
// of the classesDir
}

关键在于找到类文件:我在编译完成后使用我的构建系统运行此脚本,并将生成的类文件路径传递给它。

然而,从哪里获取类实例并不重要,主要部分是调用cfg.addAnnotatedClass()让Hibernate知道它们。


1

看起来 org.hibernate.tool.hbm2ddl.SchemaExport 类是处理 Hibernate 中的 DDL 的类。如果您检查 Spring 日志,这就是用于调用 DDL 操作的类。

然而,我不知道如何自己使用此类。


1
我使用了org.reflections来扫描类路径,以查找被 @Entity 注释的类,并将它们添加到配置中。
此外,我添加了 AuditConfiguration.getFor(cfg); 来生成审计表。
之后,我使用了已经提到的 SchemaExport 来导出模式。
    //set the package to scan
    Reflections reflections = new Reflections("my.packages.dao");

    //find all classes annotated with @Entity        
    Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Entity.class);

    //create a minimal configuration
    Configuration cfg = new Configuration();
    cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    cfg.setProperty("hibernate.hbm2ddl.auto", "create");

    for(Class<?> c : typesAnnotatedWith){
        cfg.addAnnotatedClass(c);
    }

    //build all the mappings, before calling the AuditConfiguration
    cfg.buildMappings();

    //configure Envers
    AuditConfiguration.getFor(cfg);

    //execute the export
    SchemaExport export = new SchemaExport(cfg);
    export.setOutputFile(fileName);
    export.setDelimiter(";");
    export.setFormat(true);

    export.execute(true, false, false, true);

0
this帖子中,我使用了一种基于将SessionFactory转换为Hibernate SessionFactoryImpl并使用sessionfactory内部模式导出对象的解决方案。这不是最好的解决方案,但它有效且简单。 编辑 URL已修复。

@danielmelobrasil你发布的链接假设有persistence.xml,但是这里提问者并没有使用persistence.xml。 - Himalay Majumdar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接