Dynamic Schema Creation In Hibernate


In real time,  you may need to generate database schema dynamically.

One solution to achieve this is with the usage of Hibernate as the provider for connecting to db.  The DB schema details are provided in a configuration file and can easily be modified based on the requirement. There is absolutely no need to write entity classes here. Those will be auto-generated!


1. Add the following two additional lines to your hibernate.cfg.xml file:

<property name="default_entity_mode">dynamic-map</property>
<mapping resource="test.hbm.xml"/>

“test.hbm.xml” file is my mapping xml file where i mention the db schema details to be dynamically generated.

Setting the property “default_entity_mode” to “dynamic-map” tells hibernate to generate the schema dynamically by reading the mapping file. No entity classes are needed here!

2. Below is my sample mapping file (test.hbm.xml)

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"

<class  entity-name="Student" table="Student">
<id name="id" column="STUDENT_ID" type="long">
<property  name="name" type= "string"  column="STUDENT_NAME"/>
<property name="lastName" type="string" column="STUDENT_LAST_NAME" />

3. In my servlet’s init(), i  build
hibernate session factory which will create
the database dynamically. I call this servlet from the browser using the URL
http://<server&gt;:8080/HibernateDynaMap-1.0/entity” which invokes it’s init().

2 thoughts on “Dynamic Schema Creation In Hibernate”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.