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" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class entity-name="Student" table="Student"> <id name="id" column="STUDENT_ID" type="long"> <generator/> </id> <property name="name" type= "string" column="STUDENT_NAME"/> <property name="lastName" type="string" column="STUDENT_LAST_NAME" /> </class> </hibernate-mapping>
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>:8080/HibernateDynaMap-1.0/entity” which invokes it’s init().
2 thoughts on “Dynamic Schema Creation In Hibernate”
Hello. Great job. I did not imagine this. This is a excellent story. Thanks!
Thank You, Edmundo!