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:
It is a POJO class that represents the object persistent in the database.
Java
importjavax.persistence.*;
@Entity
publicclassStudent {
@Id
privateintid;
privateString name;
privateintstd;
publicStudent() {
}
publicStudent(intid, String name, intstd) {
this.id = id;
this.name = name;
this.std = std;
}
publicintgetId() {
returnid;
}
publicvoidsetId(intid) {
this.id = id;
}
publicString getName() {
returnname;
}
publicvoidsetName(String name) {
this.name = name;
}
publicintgetStd() {
returnstd;
}
publicvoidsetStd(intstd) {
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:
The following details will be added to the database:
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 doesn’t exist in the database or session cache.
It throws ObjectNotFoundException if the object doesn’t exist in the database or session cache.
It returns fully initialized objects which may require multiple database classes. Therefore it affects the performance of the application.
It returns a proxy object and initializes the object only if any method is called on the object(other than getId()). Therefore it results in better performance.
get() is used to fetch an object when it is not sure whether the object exists or not.
load() is used to fetch an object if it is sure that object exists.