The Wayback Machine - https://web.archive.org/web/20240926134000/https://www.geeksforgeeks.org/automatic-table-creation-using-hibernate/
Open In App

Automatic Table Creation Using Hibernate

Last Updated : 19 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Hibernate is a Java framework that implements ORM(Object Relational Mapping) design pattern. It is used to map java objects into a relational database. It internally uses JDBC(Java Database Connectivity), JTA(Java Transaction API), and JNDI(Java Naming and Directory Interface). It helps to make java objects persist in the database without losing their state, thus, named Hibernate. It can be used to perform all the CRUD operations without having to write SQL queries. Hibernate framework can be used to create tables in the database automatically. Below property is added in the configuration file to create tables automatically.

<property name=”hibernate.hbm2ddl.auto”>create</property>

“hibernate.hbm2ddl.auto” property accepts the following values:

  • create: If the value is created, Hibernate creates a new table in the database when the SessionFactory object is created. In case, a table exists in the database with the same name, it deletes the table along with data and creates a new table.
  • update: If the value is updated then hibernate first validates whether the table is present in the database or not , if present alters that table as per the changes, if not creates a new one.
  • validate: If the value is validated then hibernate only verifies whether the table is present or not if the table does not exist then throws an exception.
  • create-drop: If the value is create-drop then hibernate creates a new table when SessionFactory is created, performs the operation, and deletes the table when SessionFactory is destroyed. This value is used for testing the hibernate code.
  • none: It does not make any changes to the schema.

Below is an example demonstrating the automatic table creation in hibernate using the MySQL database.

Example Project

hibernate.cfg.xml file:

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.hbm2ddl.auto">create</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/demo</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <mapping resource="Student.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>


Student.hbm.xml file:

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate Mapping DTD 3.0//EN" 
<hibernate-mapping>
    <class name="p1.Student" table="student">
    <id name="id"></id>
    <property name="name"></property>
    </class>
</hibernate-mapping>


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;
    }
  
}


Test.java file:

Java




package p1;
  
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
  
import beans.Student;
  
public class Test {
    public static void main(String... args) {
        try
        {
            Configuration config=new Configuration();
            config.configure();
            System.out.println(config);
            SessionFactory sessionFactory=config.buildSessionFactory();
            Session session=sessionFactory.openSession();
            System.out.println(session);
            Student s=new Student();
            s.setId(101);
            s.setName("Raghav");
            session.save(s);
            Transaction t=session.beginTransaction();
            t.commit();
        }
        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

 



Previous Article
Next Article

Similar Reads

Hibernate - Create Hibernate Configuration File with the Help of Plugin
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a java framework that is used to develop persisten
3 min read
Hibernate - Table Per Concrete Class using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
5 min read
Hibernate - Table Per Subclass using Annotation
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
6 min read
Hibernate - Table Per Hierarchy using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
6 min read
Hibernate - Table Per Subclass Example using XML File
In Table Per Subclass, subclass tables are mapped to the Parent class table by primary key and foreign key relationship. In a Table per Subclass strategy : For each class of hierarchy there exist a separate table in the database.While creating the database tables foreign key relationship is required between the parent table and the child table.To p
5 min read
Hibernate - Table Per Hierarchy using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
8 min read
Hibernate - Table Per Concrete Class Using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
7 min read
Spring Hibernate Configuration and Create a Table in Database
Spring Boot is used to develop REST web services and Microservices. Spring Boot reduces the configuration and setup time required for spring projects. Hibernate (Java ORM Framework) provides a framework for mapping an object-oriented domain to a relational database table like MySQL, Oracle, and PostgreSQL. Spring Boot Hibernate is used in the java
5 min read
Hibernate Example using XML in Eclipse
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XM
6 min read
Hibernate - Logging By Log4j Using Properties File
Apache log4j is a java-based logging utility. Apache log4j role is to log information to help applications run smoothly, determine what’s happening, and debug processes when errors occur. log4j may logs login attempts (username, password), submission form, and HTTP headers (user-agent, x-forwarded-host, etc.) into the log file or database. Apache l
2 min read
Hibernate - Logging by Log4j using xml File
The process of Hibernate Logging by Log4j using an XML file deals with the ability of the computer programmer to write the log details of the file he has created by executing it permanently. The most important tools in Java language like the Log4j and Log back frameworks. These frameworks in Java language help the programmer to install and initiate
5 min read
CRUD Operations using Hibernate
Hibernate is a Java framework that implements ORM(Object Relational Mapping) design pattern. It is used to map java objects into a relational database. It internally uses JDBC(Java Database Connectivity), JTA(Java Transaction API), and JNDI(Java Naming and Directory Interface). It helps to make java objects persist in the database without losing th
5 min read
How to Create a Project using Spring MVC and Hibernate 5?
Spring MVC is a popular model view controller framework that handles dependency injection at run time. Hibernate 5 is an ORM framework that acts as an abstraction over the database. It allows interaction with the underlying database by removing any implementation details which is handled by hibernate. In this article, we will integrate Spring MVC a
4 min read
Spring ORM Example using Hibernate
Spring ORM is a module of the Java Spring framework used to implement the ORM(Object Relational Mapping) Technique. It can be integrated with various mapping and persistence frameworks like Hibernate, Oracle Toplink, iBatis, etc. for database access and manipulation. This article covers an example of the integration of the Spring ORM module with Hi
5 min read
Spring Boot – Validation using Hibernate Validator
Hibernate validator offers validation annotations for Spring Boot that can be applied to the data fields within your Entity class, and allows you to follow specific rules and conditions for fields in which we are applying validators to meet your custom constraints. These annotations help ensure that the data meets all the conditions applied using t
6 min read
Hibernate Example using JPA and MySQL
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a Java framework that is used to develop persisten
4 min read
Hibernate Mapping Set using XML
In Hibernate, if we want to map one table to another with the help of a set then we use Set mapping. Set mapping can be performed if the model class or persistent class contains a set as its element. To perform set mapping, we can use a set in the mapping file. let's see how we can configure the XML mapping file for the mapping set in hibernate. Pr
5 min read
Automatic Modules in Java
The module is a collection of packages designed for reuse, and Module JAR is a regular JAR with a module descriptor in its root folder. An Automatic Module is a JAR from the classpath that has been put in the module path. Their name is derived from the jar file name by default. Hence there are enormous numbers of pre-existing libraries that you can
4 min read
Automatic Type Promotion in Overloading in Java
Before going into the actual topic, first, we need to know about method overloading and type promotions. What is Method Overloading?When a class consists of more than one method with the same name but with different signatures and return types, then we call those overloaded methods, and the process is called method overloading. Example: void method
6 min read
Automatic Resource Management in Java ( try with resource statements )
Java provides a feature to make the code more robust and to cut down the lines of code. This feature is known as Automatic Resource Management(ARM) using try-with-resources from Java 7 onwards. The try-with-resources statement is a try statement that declares one or more resources. This statement ensures that each resource is closed at the end of t
5 min read
How to Optimize String Creation in Java?
The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. The new operator is also followed by a call to a class constructor, which initializes the new object. As string creation is the process optimall
3 min read
Java Object Creation of Inherited Class
In Java, being an object-oriented language, objects inside a class is created with help of constructors. When it comes down to inheritance in Java we are basically dealing with deriving a class from another class. Now let us understand inheritance a step deeper so when a particular class inherits a class we do have a keyword that we use in order to
3 min read
Hibernate - Annotations
Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and f
7 min read
Introduction to Hibernate Framework
Prerequisite : JDBC Need of Hibernate Framework Hibernate is used to overcome the limitations of JDBC like: JDBC code is dependent upon the Database software being used i.e. our persistence logic is dependent, because of using JDBC. Here we are inserting a record into Employee table but our query is Database software-dependent i.e. Here we are usin
4 min read
Hibernate - Cache Eviction with Example
Caching in Hibernate means storing and reusing frequently used data to speed up your application. There are two kinds of caching: Session-level and SessionFactory-level. Level 1 cache is a cache that stores objects that have been queried and persist to the current session. This cache helps to reduce the number of database round trips by storing obj
9 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question has 4 solutions. Via Bag Mapping, in Hibernate, w
4 min read
Difference between JDBC and Hibernate in Java
Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let's understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate. Before getting into the difference
2 min read
Hibernate Lifecycle
Here we will learn about Hibernate Lifecycle or in other words, we can say that we will learn about the lifecycle of the mapped instances of the entity/object classes in hibernate. In Hibernate, we can either create a new object of an entity and store it into the database, or we can fetch the existing data of an entity from the database. These enti
4 min read
Java - JPA vs Hibernate
JPA stands for Java Persistence API (Application Programming Interface). It was initially released on 11 May 2006. It is a Java specification that gives some functionality and standard to ORM tools. It is used to examine, control, and persist data between Java objects and relational databases. It is observed as a standard technique for Object Relat
4 min read
Spring Boot - Integrating Hibernate and JPA
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Article Tags :
Practice Tags :