michal.kreuzman
michal.kreuzman

Reputation: 12390

Getting SQL script from Hibernate update

I'm looking for way to get the SQL update script when Hibernate automatically updates tables.

I'm using hibernate.hbm2ddl.auto=update in development environment only, and I need SQL script that updates tables for production.

I want these SQL scripts in txt format for revision and potential edit.

How can this be done? Thanks for any advice.

Upvotes: 1

Views: 2452

Answers (2)

csviri
csviri

Reputation: 1229

org.hibernate.cfg.Configuration class has method:

public java.lang.String[] generateSchemaUpdateScript( Dialect, DatabaseMetadata)


what generates the reqiured update script.

I've just implemented this in grails:

configuration = new DefaultGrailsDomainConfiguration(
                    grailsApplication: grailsApplication,
                    properties: props) 
//this extends hibernate config

Connection c = SessionFactoryUtils.getDataSource(sessionFactory).getConnection(props.'hibernate.connection.username', props.'hibernate.connection.password')
<br/>md = new DatabaseMetadata(c, DialectFactory.buildDialect(props.'hibernate.dialect'))

configuration.generateSchemaUpdateScript(DialectFactory.buildDialect(props.'hibernate.dialect'), md)
)
check SchemaExport script in grails, for further information, it uses hibernate to generate schema.


(I had to implent is as a service because we have external domain model)

Upvotes: 0

Ben Hoffstein
Ben Hoffstein

Reputation: 103355

There are some suggestions and general discussion here.

In a nutshell, you can turn on logging (to standard output):

hibernate.show_sql=true

Alternatively, if you use log4j, you can add this to your log4j.properties file:

log4j.logger.org.hibernate.SQL=DEBUG

Both of these approaches are going to output Hibernate's prepared statements with parameters (so the parameter values themselves are not inline). To get around this, you could use an interceptor like P6Spy. Details on that can be found here.

Upvotes: 2

Related Questions