Tuesday, June 29, 2010

Generate DDL to a text file using Hibernate rather than firing it to DB.

Problem Description:
I never liked the idea of using hbm2ddl.auto attribute directly inside hibernate.cfg.xml file directly . Suppose you have this mapping equal to "update" or "create" in local/development environment and somehow you change the connection related parameters to connect to production environment .Now if forget to change/disable the hbm2ddl.auto property,what next ?? This is really really dangerous .But then how to generate the DDL ?

I do not want the risk of using hbm2ddl.auto , but I want the DDL .

Solution:
Using the following code which uses SchemaExport class of Hibernate , generate the text file which contains the DDL.Copy that DDL and fire to DB as per your requirement .

Sample code:
public class SchemaExportUtil
{
public static void main(String[] args)
{

Configuration configuration = new Configuration();
configuration.configure();
SchemaExport schemaExport = new SchemaExport(configuration);
boolean generateScript = true;
boolean fireScriptToDB = false;
String schemaExportFileName = "c://script/DDL.txt";
schemaExport.setOutputFile(schemaExportFileName);
schemaExport.create(generateScript, fireScriptToDB);

}

}

How to use this program :

If the mappings are correct scripts will be generated according to the dialect mentioned in hibernate.cfg.xml.

If you the script to be fired at the database , just set fireScriptToDB=true.Otherwise it will write the DDL to the mentioned text file.The choice is yours now !

No comments:

Post a Comment