有很多关于如何使用 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 知道它们。
关于java - 如何为 hibernate > 4.3 导出模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22733631/