Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Hibernate- Automatic table Creation

As we have seen the 'Employee' class:


class Employee{

  int id;
  String name;

  public int getId() {
   return id;
  }
  public void setId(int id) {
   this.id = id;
  }
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
}


And the 'EMPLOYEE' table:

CREATE TABLE EMPLOYEE (ID INTEGER, NAME VARCHAR);

Has the same structure. But we have to create the table 'EMPLOYEE' manually by logging into the database.

What if we did not want to create the table ourselves, instead ask Hibernate to do it for us.

Yes, Hibernate provides a way to do so. i.e. hbm2ddl.auto.

All we have to do is set the property 'hbm2ddl.auto' to 'create' in hibernate.cfg.xml and Hibernate will create the table for you.


hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
    <property name="hibernate.dialect">
    org.hibernate.dialect.PostgreSQLDialect
    </property>
    <property name="hibernate.connection.driver_class">
    com.postgresql.Driver
    </property>
    <property name="hibernate.connection.url">
    jdbc:postgresql://localhost/newDb
    </property>
    <property name="hibernate.connection.username">
    myuser
    </property>
    <property name="hibernate.connection.password">
    Password123
    </property>

    <property name="hbm2ddl.auto">
    create
    </property>

    <mapping resource="Employee.hbm.xml"/>

   </session-factory>
</hibernate-configuration>

Along with the other properties set the 'hbm2ddl.auto' to 'create'.

<property name="hbm2ddl.auto">
   create
</property>

and Hibernate will create the table for you.

hbm2ddl.auto

hbm2ddl.auto gives us four options:

1. Create : It checks if a table exists, if so it drops the current table. Then creates a new one.

2. Create-Drop : Creates the tables and drops it when the SessionFactory is closed.

3. Validate : It only validates that the schema matches the mapping files.

4. Update : It checks if a table exists and updates or creates a new table. But does not drop a table if it exists.
Note : Please do not try in production environment.