Searching...
Friday, 16 August 2013

Hibernate Insert/Select/Update/Delete Example

11:09
In this example we will how CRUD operation in hibernate. Hibernate Session interface offering the CRUD operations of mapped entity classes. Let us consider Student entity to do all these operation.

Software Used

Java 1.7
Hibernate 3
MySql 5
Eclipse Juno

1. Create a Java project

Create a Java project and update Hibernate jars and Mysql driver jar in to build path. (Download Hibernate , MySql Driver)
image

2. Create a Student Entity


package com.pretech;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student", catalog = "hibernateschema")
public class Student  {
    @Id
    @Column(name = "name", unique = true, nullable = false, length = 100)
    private String name;

    @Column(name = "standard", unique = true, nullable = false, length = 200)
    private String standard;
   

    public String getStandard() {
        return standard;
    }

    public void setStandard(String standard) {
        this.standard = standard;
    }

    public String getName() {
        return name;
    }

    public void setName(String string) {
        name = string;
    }

    public String toString() {
        return name;
    }
}

3. Create Hibernate config file (hibernate.cfg.xml)


<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="studentFactory">
            <property name="connection.driver_class">
                 com.mysql.jdbc.Driver
            </property>
        <property name="connection.url">
             jdbc:mysql://localhost:3306/hibernateschema
        </property>
        <property name="connection.username">
             root
        </property>
        <property name="connection.password">
            root
        </property>
            <property name="connection.pool_size">5</property>
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
             <property name="hbm2ddl.auto">update</property>
             <mapping class="com.pretech.Student"></mapping>
    </session-factory>
</hibernate-configuration>

4.Create a Main program

package com.pretech;

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

public class StudentMain {

    private static SessionFactory sessionFactory;

    public static void main(String[] args) {

        try {
            sessionFactory = new Configuration().configure("hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        Session session = sessionFactory.openSession();
       
        //Inserting Student Records
        Transaction tx = session.beginTransaction();
        Student student = new Student();
        student.setName("Raj");
        student.setStandard("10th Standard");
        session.save(student);
        tx.commit();
               
        System.out.println("Inserted Student details");
       
        //Selecting Student Records
        Object object = session.load(Student.class, "Raj");
        Student stud = (Student) object;
        System.out.println("Selected Student details");

        System.out.println("Student Name: " + stud.getName());
        System.out.println("Student Standard: " + stud.getStandard());

        //Update Student Details
        System.out.println("Updating Student details ");
        Transaction tx1 = session.beginTransaction();
        stud.setStandard("Plus one");
        session.update(stud);
        tx1.commit();
       
        Object object1 = session.load(Student.class, "Raj");
        Student stud1 = (Student) object1;
        System.out.println("Student details after updating");

        System.out.println("Student Name: " + stud1.getName());
        System.out.println("Student Standard: " + stud1.getStandard());
       
        System.out.println("Deleting Student records");
        Transaction tx2 = session.beginTransaction();
       
        //Deleting Student records
        session.delete(stud1);
        tx2.commit();

        System.out.println("Student Deleted successfully");
        if (session != null)
            session.close();
    }

}

5. Output

Run the main program and see below output
Hibernate: insert into hibernateschema.student (standard, name) values (?, ?)
Inserted Student details
Selected Student details
Student Name: Raj
Student Standard: 10th Standard
Updating Student details
Hibernate: update hibernateschema.student set standard=? where name=?
Student details after updating
Student Name: Raj
Student Standard: Plus one
Deleting Student records
Hibernate: delete from hibernateschema.student where name=?
Student Deleted successfully

0 comments: