Hibernate Annotation – Creating table from java

Hibernate is a very efficient framework for database.  Users can create tables from pure java file without creating using SQL queries.

Let us see how to create table from pure java file(POJOS) using annotations in Hibernate.

Directory Structure:
structure

employee.java

package com.javainfinite.pojo;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table (name="Employee")
public class employee implements Serializable {
    
    @Id
    @GeneratedValue
    @Column(name="Employee_ID")
    private int eid;
    @Column(name="Employee_Name")
    private String ename;
    @Column(name="Employee_Password")
    private String epass;
    
    public int getEid() {
        return eid;
    }

    public void setEid(int eid) {
        this.eid = eid;
    }
    

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getEpass() {
        return epass;
    }

    public void setEpass(String epass) {
        this.epass = epass;
    }
}

@Entity – Used to indicate the class a entity bean for the hibernate to understand
@Table – The name of the table that is to be created in the database (Optional). If this is not mentioned, By default hibernate creates table with java class name (In this case table name will be employee)
@Id – Marks the primary key for the table – In this case we have marked eid as primary key
@GeneratedValue – This is similar to auto_increment in MySQL
@Column (name=” “) – Column name in table for that field

NewHibernateUtil.java

package com.javainfinite.pojo;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
public class NewHibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

hibernate.cfg.xml

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">URL</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.show_sql">true</property>
    <mapping class="com.javainfinite.pojo.employee"/>
  </session-factory>
</hibernate-configuration>

hbm2ddl.auto – update – Used to update the field in table, if table is not available it creates a new table
hbm2ddl.auto – create – It creates new table on every execution, if table already present it drops the table and create new one.
mapping class – The class which we have marked as @Entity – so the hibernate understands it needs to create table for the fields of that class
hibernate.show_sql – Used to show the sql query hibernate used in the application (Optional)

Execution.java

package com.javainfinite.exec;

import com.javainfinite.pojo.NewHibernateUtil;
import com.javainfinite.pojo.employee;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Execution {
    
    public static void main(String args[])
    {
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        try
        {
            Transaction transaction=session.beginTransaction();
            employee emp=new employee();
            emp.setEname("Alpha");
            emp.setEpass("123456");
            session.save(emp);
            transaction.commit();
            session.close();
            
        }
        catch(Exception e)
        {
            
        }
    }
}

Output:
op1

We can see the query used by hibernate in the output, that’s because we have mentioned hibernate.show_sql – true

op2

 

 

 

By Sri

One thought on “Hibernate Annotation – Creating table from java”

Leave a Reply

Your email address will not be published. Required fields are marked *