Last active
May 27, 2018 16:00
-
-
Save bsandhu/28f9d021507d86950b6c08d084eb864b to your computer and use it in GitHub Desktop.
Run Hibernate Schema update from command line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.bsandhu.server.db | |
import org.hibernate.boot.MetadataSources | |
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl | |
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder | |
import org.hibernate.boot.registry.StandardServiceRegistryBuilder | |
import org.hibernate.boot.spi.MetadataImplementor | |
import org.hibernate.tool.hbm2ddl.SchemaUpdate | |
private const val OUT_FILE = "target/schemaUpdate.sql" | |
class UpdateDDLCreator { | |
private val dialect = "org.hibernate.dialect.MySQLDialect" | |
private val jdbcUrl = "jdbc:mysql://localhost:3306/mydb" | |
private val driver = "com.mysql.jdbc.Driver" | |
// Pass these as VM options on the command line | |
// -Dusername=xxx -Dpassword=xxx | |
private val username = System.getProperty("username") | |
private val password = System.getProperty("password") | |
/** | |
* Compares DB with changes to Java model definition and creates DDL update script | |
* | |
* https://docs.jboss.org/hibernate/orm/5.0/topical/html/bootstrap/NativeBootstrapping.html | |
*/ | |
fun run(){ | |
val props = mapOf( | |
"hibernate.dialect" to dialect, | |
"hibernate.connection.url" to jdbcUrl, | |
"hibernate.connection.username" to username, | |
"hibernate.connection.password" to password, | |
"hibernate.connection.driver_class" to driver) | |
val bsr = BootstrapServiceRegistryBuilder().build() | |
val ssrBuilder = StandardServiceRegistryBuilder(bsr) | |
ssrBuilder.applySettings(props) | |
val registry = ssrBuilder.build() | |
val metadata = MetadataSources(registry) | |
with (metadata) { | |
addAnnotatedClass(UserModel::class.java) | |
} | |
val metadataBuilder = metadata.metadataBuilder | |
metadataBuilder | |
.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ) | |
.build() | |
val exporter = SchemaUpdate(metadataBuilder?.build() as MetadataImplementor) | |
exporter.setOutputFile(OUT_FILE) | |
println("*".repeat(120)) | |
println("Writing Schema update scripts to $OUT_FILE") | |
println("Updated are NOT applied to the DB. These managed via Flyway") | |
println("*".repeat(120)) | |
exporter.execute(true, false) | |
} | |
companion object { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
UpdateDDLCreator().run() | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment