我正在尝试转换我的工作(使用Hibernate 4.x)脚本,该脚本建议从实际数据库进行迁移。这很方便,特别是当我想要跟踪更改并将它们存储在FlyWay使用的sql脚本中时。
这是我的班级:
public class SchemaGenerator {
private static Configuration cfg;
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost/test?tinyInt1isBit=false";
private static String username = "root";
private static String password = "password";
public SchemaGenerator(String packageName) throws Exception {
cfg = new Configuration();
cfg.setProperty("hibernate.hbm2ddl.auto", "update");
cfg.setProperty("hibernate.connection.driver_class", driver);
cfg.setProperty("hibernate.connection.url", url);
cfg.setProperty("hibernate.connection.username", username);
cfg.setProperty("hibernate.connection.password", password);
cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
Reflections reflections = new Reflections("com.test");
Set<Class<? extends Object>> allClasses = reflections.getTypesAnnotatedWith(Entity.class);
for (Class c : allClasses) {
cfg.addAnnotatedClass(c);
}
}
public static void validate() {
SchemaValidator schemaValidator = new SchemaValidator(cfg);
schemaValidator.validate();
}
public List<SchemaUpdateScript> createUpdateScript(DataSource dataSource, org.hibernate.dialect.Dialect dialect)
throws SQLException {
DatabaseMetadata meta = new DatabaseMetadata(dataSource.getConnection(), dialect, cfg);
List<SchemaUpdateScript> createSQL = cfg.generateSchemaUpdateScriptList(dialect, meta);
return createSQL;
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
SchemaGenerator gen = new SchemaGenerator("com.test");
Driver driver = com.mysql.jdbc.Driver.class.newInstance();
DataSource dataSource = new SimpleDriverDataSource(driver, url, username, password);
List<SchemaUpdateScript> updateCommands = gen.createUpdateScript(dataSource,
new org.hibernate.dialect.MySQL5Dialect());
if (updateCommands.size() != 0)
System.out.println("" + formatSqlSuggestionScript(updateCommands));
else
System.out.println("Already up to date");
}
private static String formatSqlSuggestionScript(List<SchemaUpdateScript> sqls) {
StringBuilder builder = new StringBuilder("\n\n****update sql suggestion:***\n\n");
for (SchemaUpdateScript str : sqls) {
builder.append("\n" + str.getScript() + ";");
}
builder.append("\n\n");
return builder.toString();
}
}
我在使用schemaValidator.validate();
时遇到了一些问题,因为它现在需要Metadata和cfg.generateSchemaUpdateScriptList(dialect, meta)
不再存在。
你有一些好的提示吗?或者现在使用Hibernate 5x可能有更好的方法吗?
答案 0 :(得分:0)
您可以实例化org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl
并使用SchemaValidator。