How to insert records in mysql table using hibernate

Share:
How To Insert Records In MySql Table Using Hibernate
Hello Java Lovers...In this Hibernate tutorial we are going to learn how to insert records in MySql DataBase Table.  

As we know hibernate is framework to simplifies the development of Java application to interact with Database. It is an opensource, lightweight ORM(Object Relational Mapping) tool. Hibernate implement's specification of JPA(Java Persistence API) for data  persistence.

ORM Tool
This tool is used to simplifies the data creation, data manipulation and data access. This ORM technique is used to map the object to data stored in Database Table.

JAVA Application > OBJECT > ORM > DATABASE.

Now comes to our tutorial purpose, so our tutorial purpose is insert the values of an object into DB Table.

Our Project Structure :
So first add required jar files as shown in the above pic and create a class Employee in package called com.nt.Domain
Employee.java
package com.nt.Domain;

public class Employee {
private int eid;
private String fname;
private String lname;
private String email;

public Employee() {
}
public Employee(int eid, String fname, String lname, String email) {
     this.eid = eid;
     this.fname = fname;
     this.lname = lname;
     this.email = email;
}
public int getEid() {
     return eid;
}

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

public String getFname() {
     return fname;
}

public void setFname(String fname) {
     this.fname = fname;
}

public String getLname() {
     return lname;
}

public void setLname(String lname) {
     this.lname = lname;
}

public String getEmail() {
     return email;
}

public void setEmail(String email) {
     this.email = email;
}

@Override
public String toString() {
     return "Employee [eid=" + eid + ", fname=" + fname + ", lname=" + lname + ", email=" + email + "]";
}
}


Now create com.nt.cfgd and in this folder create mapping file as well as configuration file as follows.

Mapping File : Employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
     <class name="com.nt.Domain.Employee" table="Employee">
      <id name="eid" column="EID"/>
      <property name="fname" column="FNAME"/>
      <property name="lname" column="LNAME"/>
      <property name="email" column="EMAIL"/>
    </class>
</hibernate-mapping>

Configuration File : hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
     <hibernate-configuration>
 <session-factory>
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost:3306/HiberNate_DB</property>
  <property name="connection.username">root</property>
  <property name="connection.password"></property>
  <property name="hibernate.hbm2ddl.auto">create</property>
  <mapping resource="/com/nt/cfgs/Employee.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

Now create a package called com.Hibernate.utils and in this package create a class
HiberNateUtilClass.java
package com.Hibernate.Utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HiberNateUtilClass {
     private static SessionFactory sessionFactory;
     static {
           try {
                Configuration cfg=new Configuration();
                cfg=cfg.configure("/com/nt/cfgs/hibernate.cfg.xml");
                sessionFactory=cfg.buildSessionFactory();
               
           } catch (Exception e) {
                System.out.println(e.getMessage());
           }
     }//end of block

     public static SessionFactory getSession() {
           return sessionFactory;
     }
}

Now create a package called com.EmpDao and in this package create an Interface
EmpDao.java
package com.EmpDao;

import com.nt.Domain.Employee;

public interface EmpDao {
     public void saveEmployee (Employee employee);
}

Now Create a package called com.EmpDaoImpl and in this package create a class who implements EmpDao interface.
EmpDaoImple.java
package com.EmpDaoImpl;

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

import com.EmpDao.EmpDao;
import com.Hibernate.Utils.HiberNateUtilClass;
import com.nt.Domain.Employee;

public class EmpDaoImple implements EmpDao{
     @Override
     public void saveEmployee(Employee employee) {
           SessionFactory sessionFactory;
           sessionFactory=HiberNateUtilClass.getSession();
           Session session=sessionFactory.openSession();
           Transaction tx=session.beginTransaction();
           try {
             session.save(employee);
             tx.commit();
             System.out.println("Object Values Saved Successfully :)");
           } catch (Exception e) {
               
           System.out.println("Sorry Some Error Occurred In EmpDaoImple class While Saving Data!");
           tx.rollback();
           }
           finally {
                session.close();
           }   
     }
}


Now create a package com.Service and in this package create a class.
InsertRecordService.java
package com.Service;

import com.EmpDaoImpl.EmpDaoImple;
import com.nt.Domain.Employee;

public class InsertRecordService {
     public static void Insert_Object_Data() {
            EmpDaoImple obj=new EmpDaoImple();
            Employee emp1=new Employee(1,"Mateen1","Mansoori1","mateewd1@gmail.com"); 
            Employee emp2=new Employee(2,"Mateen2","Mansoori2","mateewd2@gmail.com"); 
            Employee emp3=new Employee(3,"Mateen3","Mansoori3","mateewd3@gmail.com"); 
            Employee emp4=new Employee(4,"Mateen4","Mansoori4","mateewd4@gmail.com"); 
            obj.saveEmployee(emp1);
            obj.saveEmployee(emp2);
            obj.saveEmployee(emp3);
            obj.saveEmployee(emp4);
     }
}


Now create a package called com.Test and in this package create a class.
TestMain.java
package com.Test;

import com.Service.InsertRecordService;

public class TestMain {
    
     public static void main(String[] args) {
           InsertRecordService.Insert_Object_Data();
     }
}

That's All :) .... :(

Now create a DataBase and provide same name as specified in  configuration file. i.e. HiberNate_DB.nThis DataBase is empty and there is no single table present ok.


Note : No need to create table manually ,it will be created automatically when you run the application but you have to create DataBase Manually.

So Now Go To In Your Eclipse And Run The TestMain.java, If everything goes right then will get a message in your console as :
Object Values Saved Successfully :)
Object Values Saved Successfully :)
Object Values Saved Successfully :)

Object Values Saved Successfully :)

Now See Your DataBase A employee table should be there with values whatever you have inserted.

Now Click On employee Table, You Will See Data Shown As Below.

If You Found This Tutorial Helpful Then Share This Tutorial. 

No comments

You May Like Also

Programming Knowledge


Java JDK
Reversing String in Java
Java Generic Concept With Simple Example
Java Generic Objects Behavior In Non-Generic Area
Creating Connection With MySql Databse Using Java Application
Performing Database Operations Java MySql Insert Update Delete Select
Java Inserting Data in MySql Databse Table
Java Basic Login System Using MySql Database Table
JSP Login System Using MySql Databse
Jsp Servlet Login And Logout System Using Mysql Database Table
What is jdk in Java?
Exaplain inheritance in Java with example?
Exaplain polymorphism in Java with example?
Exaplain abstraction in Java with example?
Exaplain encapsulation in Java with example?
What is the use of this keyword in Java?
Explain ArrayList With Example
Explain LinkedList With Example
Explain Vector Class With Example
Explain Vector Class With Example
Generics in java with example
Behavior of generic objects
How can i pass generic class to a method in java
How to create a login system in jsp using mysql database?
How to create a login and logout system in jsp & servlet using mysql database?
How to connection a simple Java application with mysql database?
How to insert values in mysql databse usiong Java applications?
Perform insertion, retrieval, updatation and delete operations?
How to create a simple login system in java using mysql database?

PHP Login System Using MySql Database
PHP Complete Login System With Session And Logout Using MySql Database