Skip to main content

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

}


}





Comments

Popular posts from this blog

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...