如何导出hibernate模式> 4.3 [英] How to export the schema for hibernate > 4.3

查看:97
本文介绍了如何导出hibernate模式> 4.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



但是对于Hibernate 4.3来说,类 org.hibernate.ejb.Ejb3Configuration 被删除,我无法找到任何替代品。
如何以编程方式生成休眠版本> = 4.3的ddl脚本?
因为我使用spring来设置实体管理器,所以我也不必再使用persitence.xml,我想这样保留它。



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

解决方案

我用 org.reflections 来扫描类路径,这些类用@Entity注释并添加到配置中。



另外我添加了
AuditConfiguration.getFor(CFG);
生成审计表。



之后,我使用已经提到的SchemaExport导出了Schema。

  //设置包扫描
Reflections reflections = new Reflections(my.packages.dao);

//找到用@Entity
注解的所有类Set< Class<>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Entity.class);

//创建最小配置
配置cfg = new Configuration();
cfg.setProperty(hibernate.dialect,org.hibernate.dialect.PostgreSQLDialect);
cfg.setProperty(hibernate.hbm2ddl.auto,create);

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

//构建所有映射,然后调用AuditConfiguration
cfg.buildMappings();

//配置Envers
AuditConfiguration.getFor(cfg);

//执行导出
SchemaExport export = new SchemaExport(cfg);
export.setOutputFile(fileName);
export.setDelimiter(;);
export.setFormat(true);

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


There are many post on how to export programmatically a schema with hibernate (e.g. [1]).

But with Hibernate 4.3 the class org.hibernate.ejb.Ejb3Configuration got removed and I could not find any replacement for it. How can I programmatically generate the ddl script with a hibernate version >=4.3? Since I'm using spring for setting up the entity manger, I also don't have to use a persitence.xml anymore and I would like to keep it that way.

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

解决方案

I used org.reflections to scan the classpath for classes that are annotated with @Entity and added them to the configuration.

Additionally I added AuditConfiguration.getFor(cfg); to generate the Audit tables.

After that I used the already mentioned SchemaExport to export the Schema.

    //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);

这篇关于如何导出hibernate模式&gt; 4.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆