Ad Code

✨🎆 Diwali Dhamaka Offer! 🎆✨

Get 20% OFF on All Courses at Shiva Concept Solution click

Hibernate 5 Tutorials

Hibernate 5 Tutorials

 Now Hibernate 3 and 4 are deprecated and Industry prefer Hibernate 5 and Hibernate 6. You  have knowledge of Hibernate 5 also if you have knowledge Hibernate 3 and four. Many Updating added in Hibernate 5


Now I am explaining Step by Step


1)  Open Eclipse Create Maven Project, Select Internal under Category and select QuickStart archetype

2)  Add Dependency under pom.xml file of hibernate and MySQL Connector

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.scs</groupId>

  <artifactId>Hibernate5</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <packaging>jar</packaging>

  <name>Hibernate5</name>

  <url>http://maven.apache.org</url>

  

  <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>

      <dependencies>

        <dependency>

            <groupId>org.hibernate</groupId>

            <artifactId>hibernate-core</artifactId>

            <version>5.4.18.Final</version>

         </dependency>

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <version>8.0.20</version>

        </dependency>

    </dependencies>

</project>

3)  Create hibernate.cfg.xml file 

<?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.url">jdbc:mysql://localhost:3306/ierp</property>
    <property name="connection.username">root</property>
    
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
  
    <!-- 'show_sql' set true to check sql statements on console else set to false -->
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <!-- use 'create' to Create tables on application startup else use 'update'-->
    <property name="hbm2ddl.auto">create</property>
  
    <!-- JDBC connection pool -->
    <property name="connection.pool_size">5</property>
    <property name="current_session_context_class">thread</property>
 
     <!-- Domain Model classes to be mapped -->
    <mapping class="com.scs.Hibernate5.Student" />
 
</session-factory>
</hibernate-configuration>

4)  Create HibernateUtil.java file:-

package com.scs.Hibernate5;

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

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
  
    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("build SeesionFactory failed :" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
  
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
  
    public static void close() {
        // Close all cached and active connection pools
        getSessionFactory().close();
    }
  
}

5)  Create App.java file

package com.scs.Hibernate5;

import java.util.List;

import javax.persistence.TypedQuery;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
    Configuration cfg = new Configuration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Student student = new Student();
student.setRno(1003);
student.setSname("STU3");
student.setBranch("EC");
student.setFees(75000);
session.save(student);
session.getTransaction().commit();
      //  Query<Student> q = session.createQuery("From Student", Student.class);
        TypedQuery<Student> q = session.createQuery("From Student", Student.class);
        List<Student> resultList = q.getResultList();
        System.out.println("total sudents:" + resultList.size());
        
        for (Student s : resultList) {
          System.out.println("student : " + s);
        }
      }
    }

Create Student Pojo Class:

package com.scs.hibernatepractice;

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

@Entity(name = "Student")
@Table(name = "STUDENT")
public class Student {
@Id
private int rno;
@Column
private String sname;
@Column
private String branch;
@Column
private int fees;
public int getRno() {
return rno;
}
public void setRno(int rno) {
this.rno = rno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public int getFees() {
return fees;
}
public void setFees(int fees) {
this.fees = fees;
}


}

Download Tutorials


We can create hibernate.properties file in place of hibernate.cfg.xml file also.


hibernate.connection.driver_class = com.mysql.jdbc.Driver

hibernate.connection.url = jdbc:mysql://localhost:3306/ierp

hibernate.connection.username = root

hibernate.c3p0.min_size=5

hibernate.c3p0.max_size=20

hibernate.c3p0.timeout=1800

hibernate.c3p0.max_statements=50

hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

This is another example of Hibernate to perform CRUD Operation using easy way:


Create POJO CLASS:


package com.scs.hibernatepractice;


import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;


@Entity(name = "Student")

@Table(name = "STUDENT")

public class Student {

@Id

private int rno;

@Column

private String sname;

@Column

private String branch;

@Column

private int fees;

public int getRno() {

return rno;

}

public void setRno(int rno) {

this.rno = rno;

}

public String getSname() {

return sname;

}

public void setSname(String sname) {

this.sname = sname;

}

public String getBranch() {

return branch;

}

public void setBranch(String branch) {

this.branch = branch;

}

public int getFees() {

return fees;

}

public void setFees(int fees) {

this.fees = fees;

}



}



Create Hibernate.cfg.xml



<!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.url">jdbc:mysql://localhost:3306/ierp</property>

    <property name="connection.username">root</property>

    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

    <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>

  

    <!-- 'show_sql' set true to check sql statements on console else set to false -->

    <property name="show_sql">true</property>

    <property name="format_sql">true</property>

    <!-- use 'create' to Create tables on application startup else use 'update'-->

    <property name="hbm2ddl.auto">update</property>

  

    <!-- JDBC connection pool -->

    <property name="connection.pool_size">5</property>

    <property name="current_session_context_class">thread</property>

 

     <!-- Domain Model classes to be mapped -->

    <mapping class="com.scs.hibernatepractice.Student" />

 

</session-factory>

</hibernate-configuration>



Create Hibernate Operation class to implement CRUD Operation


I have used HQL Hibernate Query language for data selection and find record by branch, other method use hibernate persistent object.

 

package com.scs.hibernatepractice;


import java.util.List;


import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

import org.hibernate.query.Query;




public class HiberntaeOperation {

Configuration cfg ;

SessionFactory sf;

Session session ;

    public void addStudentRecord(int rno,String sname,String branch,int fees)

    {

    cfg= new Configuration();

sf = cfg.configure().buildSessionFactory();

session= sf.openSession();

session.beginTransaction();

Student student = new Student();

student.setRno(rno);

student.setSname(sname);

student.setBranch(branch);

student.setFees(fees);

session.save(student);

session.getTransaction().commit();

session.close();

    this.selectStudentRecord();

   }

    public void updateStudentRecord(int rno,String sname,String branch,int fees)

    {

    cfg= new Configuration();

sf = cfg.configure().buildSessionFactory();

session= sf.openSession();

session.beginTransaction();

Student student = session.get(Student.class,rno);

student.setSname(sname);

student.setBranch(branch);

student.setFees(fees);

    session.update(student);

    session.getTransaction().commit();

    session.close();

    this.selectStudentRecord();

    

    }

    public void findStudentRecord(int rno)

    {

    cfg= new Configuration();

sf = cfg.configure().buildSessionFactory();

session= sf.openSession();

session.beginTransaction();

Student student = session.get(Student.class,rno);

System.out.println("rno is "+student.getRno()+ " name is "+student.getSname() + " branch is "+student.getBranch() + " fees is "+student.getFees());

    session.close();

   // this.selectStudentRecord();

    

    }

    public void deleteStudentRecord(int rno)

    {

    cfg= new Configuration();

sf = cfg.configure().buildSessionFactory();

session= sf.openSession();

session.beginTransaction();

Student student = session.get(Student.class,rno);

session.delete(student);

    session.getTransaction().commit();

    session.close();

    this.selectStudentRecord();

    }

    

    public void selectStudentRecord()

    {

    cfg = new Configuration();

sf = cfg.configure().buildSessionFactory();

session = sf.openSession();

Query q = session.createQuery("from Student",Student.class);

List<Student> s = q.getResultList();

for(Student obj:s)

{

System.out.println("rno " + obj.getRno() + " name is "+obj.getSname());

}

         session.close();

    }

    public void selectStudentRecordByBranch(String branch)

    {

    cfg = new Configuration();

sf = cfg.configure().buildSessionFactory();

session = sf.openSession();

Query q = session.createQuery("from Student s where branch=:b",Student.class);

q.setString("b", branch);

List<Student> s = q.getResultList();

for(Student obj:s)

{

System.out.println("rno " + obj.getRno() + " name is "+obj.getSname());

}

         session.close();

    }

public static void main(String[] args) {

HiberntaeOperation obj = new HiberntaeOperation();

obj.selectStudentRecordByBranch("CS");

// obj.findStudentRecord(1001);

// obj.deleteStudentRecord(1008);

}


}





Post a Comment

0 Comments