有很多文章介绍如何使用Hibernate以编程方式导出模式(例如[1])。
但是在Hibernate 4.3中,类org.hibernate.ejb.Ejb3Configuration
被删除了,我找不到它的替代品。
如何在Hibernate版本> = 4.3中以编程方式生成ddl脚本?
由于我正在使用Spring设置实体管理器,因此我也不必再使用persitence.xml,我希望保持这种状态。
有很多文章介绍如何使用Hibernate以编程方式导出模式(例如[1])。
但是在Hibernate 4.3中,类org.hibernate.ejb.Ejb3Configuration
被删除了,我找不到它的替代品。
如何在Hibernate版本> = 4.3中以编程方式生成ddl脚本?
由于我正在使用Spring设置实体管理器,因此我也不必再使用persitence.xml,我希望保持这种状态。
关于@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知道它们。
看起来 org.hibernate.tool.hbm2ddl.SchemaExport
类是处理 Hibernate 中的 DDL 的类。如果您检查 Spring 日志,这就是用于调用 DDL 操作的类。
然而,我不知道如何自己使用此类。
//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);