Hibernate: Generating DDL

Hibernate also provides useful classes to generate DDL. The generated schema may be printed to the console, stored in a file for later use or even exported to a database. The org.hibernate.tool. hbm2ddi.SchemaExport class can be used for these purposes. The SchemaExport object is created from a given Configuration object as follows:

SchemaExport schemaExport = new SchemaExport(cfg);

The schema is then created using its create() method:

boolean print = true, export = true;

schemaExport.create(print, true);

This runs the schema creation script. The drop() method is automatically executed before running the creation script. The variables print and export indicate that the schema has to be printed to the console and exported to the database. The following is the complete source code of the program:


import org.hibernate.cfg.*;

import org.hibernate.tool.hbm2ddl.*;

public class GenerateDDL {

public static void main(String[] args) {

Configuration cfg = new Configuration();



SchemaExport schemaExport = new SchemaExport(cfg);



boolean print = true, export = true;

schemaExport.create(print, true);



The program also stores the schema in a file out.sql containing the following SQL statements:

drop table if exists tbl_book;

create table tbl_book (

no integer not null auto_increment,

name varchar(255),

pr integer,

primary key (no)


If you check the database, you will find that the table tbl_book is created by the above program.

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *