我从不让hibernate直接迁移模式。下面的类将所有必要的DDL更改转储到日志和文件中。
我建议以后将SQL放入Flyway迁移中。
public class SchemaUpdateService implements InitializingBean {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd--HHmm");
private static final Logger log = LoggerFactory.getLogger(SchemaUpdateService.class);
// Simply here to ensure a fully build up hibernate stuff.
@Autowired
LocalContainerEntityManagerFactoryBean factoryBean;
@SuppressWarnings({"deprecation", "unused"})
@Override
public void afterPropertiesSet() throws Exception {
String fileName = System.getProperty("java.io.tmpdir") + "/database-migration-" + formatter.format(LocalDateTime.now()) + ".sql";
Metadata metadata = HibernateInfoHolder.getMetadata();
SessionFactoryServiceRegistry serviceRegistry = HibernateInfoHolder.getServiceRegistry();
org.hibernate.tool.hbm2ddl.SchemaUpdate schemaUpdate = new org.hibernate.tool.hbm2ddl.SchemaUpdate();
schemaUpdate.setDelimiter(";");
schemaUpdate.setOutputFile(fileName);
schemaUpdate.setFormat(true);
log.warn("--------------------------------------------------------------------------------------------------");
log.warn("Starting SCHEMA MIGRATION lookup, please add the following SQL code (if any) to a flyway migration");
log.warn("Working on schema: " + factoryBean.getJpaPropertyMap().get("schema_name") );
schemaUpdate.execute( EnumSet.of(TargetType.SCRIPT, TargetType.STDOUT), metadata, serviceRegistry);
File file = new File(fileName);
if (file.exists() && file.length() != 0) { // migrations present.
log.warn("Migrations also written to: " + fileName);
} else if (file.exists()) { // delete empty files
log.warn("No migrations");
file.delete();
}
log.warn("END OF SCHEMA MIGRATION lookup");
log.warn("--------------------------------------------------------------------------------------------------");
}
}