Tuesday Sep 03

Generate DDL with Hibernate

PDF Print E-mail
Tuesday, 20 September 2011 08:34
AddThis Social Bookmark Button

Generate DDL using a Java class

Hibernate core provide a Java class to generate DDL. SchemaExport class can be used to generate the schema in the Database, print schema in the console or create an sql file.

To illustrate this tutorial we will use the following annotated JPA entity :

hibernate entity to be exported

package com.ubiteck.hibernate.sample;
import javax.persistence.Entity;
import javax.persistence.Id;

public class UserEntity {

    private int id;
    private String userName;
    private String password;

Let's create an enumeration with the hibernate dialects we will use to generate our sql scripts. We will use MySQL,Oracle and Sybase.

Hibernate Dialect Schema Export enumeration

    enum Dialect {

	private String className;

	private Dialect(String className) {
	    this.className = className;

	public String getClassName() {
	    return className;

Let's make the generator class. In the following class we are using SchemaExport class to do the job. Because we will not export in the database we don't need to provide a full set of configuration. We are just passing the database type as an hibernate dialect and a bunch of class. In the following example we will use only one entity class (User Entity).

Hibernate DDL Generator

public class HibernateDDLGenerator {
 public static void main(String[] args) { new HibernateDDLGenerator().execute(Dialect.ORACLE,UserEntity.class);
  private void execute(Dialect dialect, Class<?>... classes) {
 	 AnnotationConfiguration configuration = new AnnotationConfiguration();
	 configuration.setProperty(Environment.DIALECT, dialect.getClassName());
	 for (Class<?> entityClass : classes) {
	SchemaExport schemaExport = new SchemaExport(configuration);
	schemaExport.setOutputFile(String.format("%s_%s.%s ", new Object[] {"ddl", dialect.name().toLowerCase(), "sql" }));
	boolean consolePrint = true;
	boolean exportInDatabase = false;
	schemaExport.create(consolePrint, exportInDatabase);

The result of the execution is a file (ddl_oracle.sql) containing the following SQL to create our entity table.

sql script for hibernate entities

    drop table UserEntity cascade constraints;

    create table UserEntity (
        id number(10,0) not null,
        password varchar2(255 char),
        userName varchar2(255 char),
        primary key (id)

DDL script for Oracle

Tags: java , tutorial , import , class , hibernate , generate , entity , schema , illustrate , javax.persistence.entity;import

Java Tutorial on Facebook