Automatic Table Creation Using Hibernate (original) (raw)

Last Updated : 23 Apr, 2026

Hibernate can automatically create and manage database tables using configuration settings, reducing the need to write SQL manually. This feature is controlled by the hibernate.hbm2ddl.auto property, which defines how schema generation should behave. It is especially useful during development and testing for quick database setup and updates.

**Syntax (Configuration Property):

value

"hibernate.hbm2ddl.auto" property accepts the following values:

Step-by-Step Project Implementation

Follow below steps to demonstrating the automatic table creation in hibernate using the MySQL database.

Step 1: Create Java Project

Create a simple Java project (e.g., in Eclipse/IntelliJ) and Add Hibernate and MySQL dependencies (JARs or Maven)

Step 2: Create Database

Create a database in MySQL:

CREATE DATABASE demo;

Step 3: Create Hibernate Configuration File

Create a hibernate configuration file hibernate.cfg.xml file.

**hibernate.cfg.xml file:

XML `

create org.hibernate.dialect.MySQL5Dialect com.mysql.cj.jdbc.Driver jdbc:mysql://localhost:3306/demo root root

`

Step 4: Create Mapping File

Create a mapping file Student.hbm.xml file.

**Student.hbm.xml file:

XML `

`

Step 5: Create Entity Class

Create the Entity Class named as Student.java.

**Student.java file:

Java `

package p1;

public class Student {

private int id;
private 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;
}

}

`

Step 6: Create Main Class

Create Main class Test.java to write the logic .

**Test.java file:

Java `

package p1;

import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration;

import p1.Student;

public class Test { public static void main(String... args) { try { Configuration config = new Configuration(); config.configure();

        SessionFactory sessionFactory = config.buildSessionFactory();
        Session session = sessionFactory.openSession();

        // start transaction first
        Transaction t = session.beginTransaction();

        Student s = new Student();
        s.setId(101);
        s.setName("Raghav");

        session.save(s);

        // Commit after operation
        t.commit();

        session.close();
        sessionFactory.close();

    } catch (Exception e) {
        System.out.println(e);
    }
}

}

`

**Output:

A new table 'student' is created and data from the Student class object is mapped into the table.

Output