How to export schema from a spring configured hibernate

From Coder's Log

Jump to: navigation, search

While there is an ant task for hibernate tools to do the schema export, It becomes quite difficult to run maintain all hibernate configuration inside a spring xml and still be able to use those tools. The following code will use spring defined beans to generate schema much like the ant task would generate it from hibernate xml files.

The code assumes the following beans

  • annotatedClasses - java.lang.List<Class> which lists all the classes that are annotated as @Entity


public class HibernateSchemaExporter {
	public static void main(String[] args) throws Exception {
		export(true,"org.hibernate.dialect.HSQLDialect");
	}
	
	public static void export(boolean createOnly, String dialect) throws Exception{
		GenericApplicationContext context = new GenericApplicationContext();
		XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
		xmlReader.loadBeanDefinitions(new FileSystemResource("WEB-INF/applicationContext.xml"));
		context.refresh();
		export(context,createOnly,dialect);
	}
	public static void export(GenericApplicationContext context,boolean createOnly, String dialect) throws Exception{
		AnnotationConfiguration configuration=new AnnotationConfiguration();
		ArrayList<String> annotatedClasses=(ArrayList)context.getBean("annotatedClasses");
		configuration.setProperty("hibernate.dialect", dialect);
		for(String annotatedClass:annotatedClasses)
			configuration.addAnnotatedClass(Class.forName(annotatedClass));
		SchemaExport export = new SchemaExport(configuration);
		export.setOutputFile("sql.ddl");
		export.setDelimiter(";");		
		export.execute(false, false,false,createOnly);
	}	
}
Personal tools