0% found this document useful (0 votes)
11 views

CRUD Operations Using Hibernate

Uploaded by

nebad87145
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

CRUD Operations Using Hibernate

Uploaded by

nebad87145
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

3/21/24, 8:45 AM CRUD Operations using Hibernate - GeeksforGeeks

CRUD Operations using Hibernate


Hibernate is a Java framework that implements ORM(Object Relational
Mapping) design pattern. It is used to map java objects into a relational
database. It internally uses JDBC(Java Database Connectivity), JTA(Java
Transaction API), and JNDI(Java Naming and Directory Interface). It helps to
make java objects persist in the database without losing their state, thus,
named Hibernate. It can be used to perform all the CRUD operations without
having to write SQL queries. CRUD refers to database operations:

C -> Create/Insert
R -> Retrieve
U -> Update
D -> Delete

Given below are the examples that illustrate the use of Hibernate to perform
CRUD operations. All the examples use MySQL for database management and
‘student_info’ as a sample database.

Example Project

SessionFactoryProvider.java:

It is used to create and return a SessionFactory object:

Video will
play after…

https://www.geeksforgeeks.org/crud-operations-using-hibernate/ 1/14
3/21/24, 8:45 AM CRUD Operations using Hibernate - GeeksforGeeks

Java

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

public class SessionFactoryProvider {


public static SessionFactory provideSessionFactory()
{
Configuration config=new Configuration();
config.configure();
return config.buildSessionFactory();
}
}

Student.java:

It is a POJO class that represents the object persistent in the database.

Java

import javax.persistence.*;
×
@Entity
public class Student {
@Id
private int id;
private String name; Video will
private int std; play after…

public Student() {
}
https://www.geeksforgeeks.org/crud-operations-using-hibernate/ 2/14
3/21/24, 8:45 AM CRUD Operations using Hibernate - GeeksforGeeks

public Student(int id, String name, int std) {


this.id = id;
this.name = name;
this.std = std;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStd() {
return std;
}
public void setStd(int std) {
this.std = std;
}
}

hibernate.cfg.xml:

It is a configuration file used to provide database details, mapping resources,


etc.. ‘hibernate.hbm2ddl.auto’ property in the configuration file is set to ‘create’
for creating tables in the database automatically. If the table already exists in
the database ‘hibernate.hbm2ddl.auto’ is set to ‘update’. For creating tables
automatically:

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="hibernate.hbm2ddl.auto">create</property>
Video will
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</
play after…
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/stud
<property name="hibernate.connection.username">root</property>

https://www.geeksforgeeks.org/crud-operations-using-hibernate/ 3/14
3/21/24, 8:45 AM CRUD Operations using Hibernate - GeeksforGeeks

<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</pr
<mapping class="beans.Student"></mapping>
</session-factory>
</hibernate-configuration>

For inserting, retrieving, updating, or deleting records from an existing table in


the database:

hibernate.cfg.xml:

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="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/stud
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</pr
<mapping class="beans.Student"></mapping>
</session-factory>
</hibernate-configuration>

Creating a table in the database and inserting a new record:

The following method of ‘org.hibernate.Session’ is used to persist the object in


the database:

Serializable save(Object object) ×

Video will
play after…

https://www.geeksforgeeks.org/crud-operations-using-hibernate/ 4/14
3/21/24, 8:45 AM CRUD Operations using Hibernate - GeeksforGeeks

School of Electrical Engineering,


KIIT
School of Electrical Engineering, KIIT has been
playing a vital role in producing electrical

Create.java:

Java

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

public class Create {


public static void main(String[] args)
{
SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory
Session session=sessionFactory.openSession();
Transaction t=session.beginTransaction();

Student s=new Student(101,"John",10);


session.save(s);
t.commit();

sessionFactory.close();
}
} ×

The following details will be added to the database:


Video will
play after…

https://www.geeksforgeeks.org/crud-operations-using-hibernate/ 5/14
3/21/24, 8:45 AM CRUD Operations using Hibernate - GeeksforGeeks

Retrieving data from the database:

The following two methods are used to retrieve the data from the database:

<T> T get(Class<T> entityType, Serializable id)

<T> T load(Class<T> theClass, Serializable id)

Difference between get() and load():

get() load()

It returns null if the object It throws ObjectNotFoundException if the


doesn’t exist in the database or object doesn’t exist in the database or session
session cache. cache.

It returns fully initialized objects


It returns a proxy object and initializes the
which may require multiple
object only if any method is called on the
database classes. Therefore it
object(other than getId()). Therefore it results
affects the performance of the
in better performance.
application. ×

get() is used to fetch an object


load() is used to fetch an object if it is sure that
when it is not sure whether the
object exists.
object exists or not. Video will
play after…

Retrieve.java:

https://www.geeksforgeeks.org/crud-operations-using-hibernate/ 6/14
3/21/24, 8:45 AM CRUD Operations using Hibernate - GeeksforGeeks

Java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utilities.SessionFactoryProvider;

public class Retrieve {


public static void main(String[] args)
{
SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory
Session session=sessionFactory.openSession();

Student s=session.get(Student.class, 101);


System.out.println("Id : "+s.getId());
System.out.println("Name : "+s.getName());
System.out.println("Class : "+s.getStd());

sessionFactory.close();
}

JavaThe
Arrays Java Strings
following Javawill
details OOPsbe fetched
Java Collection Java database:
from the 8 Tutorial Java Multithreading Java Exception H

If an object doesn’t exist in database, get() returns null whereas load() throws
ObjectNotFoundexception.

Retrieve.java:

Java
×
package crudOperations;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import beans.Student;
Video will
import utilities.SessionFactoryProvider;
play after…

public class Retrieve {


public static void main(String[] args)

https://www.geeksforgeeks.org/crud-operations-using-hibernate/ 7/14
3/21/24, 8:45 AM CRUD Operations using Hibernate - GeeksforGeeks

{
SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory
Session session=sessionFactory.openSession();

System.out.println("Fetching object using get:");


Student s1=session.get(Student.class, 102);
System.out.println(s1);
System.out.println("Fetching object using load:");
Student s2=session.load(Student.class,102);
System.out.println(s2);

sessionFactory.close();
}
}

Output:

Updating a record in the database:

Update.java:

Java

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

public class Update {


public static void main(String[] args)
{
SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory
Session session=sessionFactory.openSession(); ×
Transaction t=session.beginTransaction();

Student s=session.get(Student.class, 101);


s.setStd(11);
session.save(s); Video will
t.commit(); play after…

sessionFactory.close();
}

https://www.geeksforgeeks.org/crud-operations-using-hibernate/ 8/14
3/21/24, 8:45 AM CRUD Operations using Hibernate - GeeksforGeeks

The following record will be updated:

Deleting a record from the database:

The following method of ‘org.hibernate.Session’ is used to delete an object:

void delete(Object object)

Delete.java:

Java

package crudOperations;

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

import beans.Student;
import utilities.SessionFactoryProvider;

public class Delete {


public static void main(String[] args)
{ ×
SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory
Session session=sessionFactory.openSession();
Transaction t=session.beginTransaction();

Student s=session.get(Student.class, 101);


Video will
session.delete(s);
play after…
t.commit();

sessionFactory.close();

https://www.geeksforgeeks.org/crud-operations-using-hibernate/ 9/14
3/21/24, 8:45 AM CRUD Operations using Hibernate - GeeksforGeeks

}
}

Output:

Feeling lost in the vast world of Backend Development? It's time for a change!
Join our Java Backend Development - Live Course and embark on an exciting
journey to master backend development efficiently and on schedule.
What We Offer:

Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks

Maximize your earnings for your published articles in Dev Scripter 2024! Showcase
expertise, gain recognition & get extra compensation while elevating your tech profile.

Last Updated : 31 Oct, 2022 2

Previous Next

Hibernate Validator Hibernate Example without IDE

×
Share your thoughts in the comments Add Your Comment

Video will
Similar Reads play after…

https://www.geeksforgeeks.org/crud-operations-using-hibernate/ 10/14

You might also like