我最近将Hibernate从5.0更新到5.1,SchemaExport
API已更改。迁移文档提到了此更改,但未解释如何使用较新的API。此外,我还没有找到任何其他支持样本来解决突破性变化。
答案 0 :(得分:4)
我偶然发现了这个代码差异,帮助我解决了API中的差异:https://gitlab.nuiton.org/nuiton/topia/commit/0c57f073ad879a981e9fa3315f0e04669a57858b
这是我的代码,它将标记有@Entity注释的任何Class的模式导出到输出窗口。
static void getDDL(String packageName, String propertiesFile) throws IOException {
MetadataSources metadata = new MetadataSources(
new StandardServiceRegistryBuilder()
.loadProperties(propertiesFile)
.build());
new Reflections(packageName)
.getTypesAnnotatedWith(Entity.class)
.forEach(metadata::addAnnotatedClass);
//STDOUT will export to output window, but other `TargetType` values are available to export to file or to the db.
EnumSet<TargetType> targetTypes = EnumSet.of(TargetType.STDOUT);
SchemaExport export = new SchemaExport();
export.setDelimiter(";");
export.setFormat(true);
export.createOnly(targetTypes, metadata.buildMetadata());
}
答案 1 :(得分:0)
leojh回答有效并创建了脚本。但挂起并永不停止执行?似乎首先导出然后导入。只想要导出......为什么Java不会退出?
输出:
INFO Dialect:Using dialect: org.hibernate.dialect.MySQL5Dialect
INFO SchemaExport:Running hbm2ddl schema export
INFO SchemaCreatorImpl:Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@1bd39d3c'
类别:
String file="export.sql";
try {
MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder()
.loadProperties(new File(DatabaseCreator.class.getClassLoader().getResource("hibernate.cfg.xml").getFile()))
.build());
new Reflections("ch.abc.mapping").getTypesAnnotatedWith(Entity.class).forEach(metadata::addAnnotatedClass);
EnumSet<TargetType> targetTypes = EnumSet.of(TargetType.SCRIPT);
new File(file).delete();
SchemaExport export = new SchemaExport();
export.setDelimiter(";");
export.setFormat(true);
export.setOutputFile(file);
export.execute(targetTypes, SchemaExport.Action.CREATE, metadata.buildMetadata());
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}