Hibernate
#hibernate
hibernate is a framework, which is developed by gavin king in 2001.
hibernate is a ORM tool..
## what is ORM tool?
---
- ORM stands for object relational mapping tool.
- by using ORM tool, we can mapped object with table, hence we can perform CRUD
operation easily.
- object can be mapped in xml and annotation way.
- in market there are many ORM tool available like EJB, EJB2, struct, struct2, hibernate,
TopLinks, iBatis
-
---
Hibernate Features
1. ✅ Open source
2. ⚙️ Automatic table creation
3. 💻 HQL, HCQL (Hibernate Query Language / Hibernate Criteria Query Language)
4. 🔗 Complex join support
5. 📄 Fetch records from multiple tables
6. 🧩 Table relation management
7. 🔄 Fetching technique (e.g., lazy/eager loading)
8. 🗃️ Caching technique support (1st level & 2nd level)
What is hbm.xml ?
In Hibernate, hbm.xml is an XML file which stands for Hibernate Mapping XML file.
By using hbm.xml , we can map objects in an XML way.
In hbm.xml , <hibernate-mapping> , <class> , <id> , <generator> , <property> tags
can be used.
<property name="name" type="java.lang.String"/>
<property name="designation" type="java.lang.String"/>
<property name="company" type="java.lang.String"/>
<property name="salary" type="double(10,2)"/>
For every different object, we have to create a separate hbm.xml file.
This file can be located in src/main/java or classpath.
<property name="name" type="java.lang.String"/>
<property name="designation" type="java.lang.String"/>
<property name="company" type="java.lang.String"/>
<property name="salary" type="double(10,2)"/>
<property name="name" type="java.lang.String"/>
<property name="designation" type="java.lang.String"/>
<property name="company" type="java.lang.String"/>
<property name="salary" type="double(10,2)"/>
<property name="name" type="java.lang.String"/>
<property name="designation" type="java.lang.String"/>
<property name="company" type="java.lang.String"/>
<property name="salary" type="double(10,2)"/>
<property name="name" type="java.lang.String"/>
<property name="designation" type="java.lang.String"/>
<property name="company" type="java.lang.String"/>
<property name="salary" type="double(10,2)"/>
<property name="name" type="java.lang.String"/>
<property name="designation" type="java.lang.String"/>
<property name="company" type="java.lang.String"/>
<property name="salary" type="double(10,2)"/>
<property name="name" type="java.lang.String"/>
<property name="designation" type="java.lang.String"/>
<property name="company" type="java.lang.String"/>
<property name="salary" type="double(10,2)"/>
<property name="name" type="java.lang.String"/>
<property name="designation" type="java.lang.String"/>
<property name="company" type="java.lang.String"/>
<property name="salary" type="double(10,2)"/>
<property name="name" type="java.lang.String"/>
<property name="designation" type="java.lang.String"/>
<property name="company" type="java.lang.String"/>
<property name="salary" type="double(10,2)"/>
<property name="name" type="java.lang.String"/>
<property name="designation" type="java.lang.String"/>
<property name="company" type="java.lang.String"/>
<property name="salary" type="double(10,2)"/>
What is cfg.xml?
In Hibernate, cfg.xml is an XML file, which stands for Hibernate configuration XML file.
In cfg.xml , configuration of Hibernate will be done.
In cfg.xml , <hibernate-configuration> , <session-factory> , <property> ,
<mapping> etc. tags can be used.
Default name of cfg.xml file can be set as a hibernate.cfg.xml file.
In application, there can be only one cfg.xml file.
This file can be located in src/main/java or classpath.
<property name="hibernate.connection.driver_class">
com.mysql.cj.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/jap78
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL8Dialect
</property>
<property name="hibernate.hbm2ddl.auto">
update
</property>
<property name="hibernate.show_sql">
true
</property>
<property name="hibernate.format_sql">
true
</property>
<mapping resource="Employee.hbm.xml"/>
SessionFactory
SessionFactory is an interface, which is located in org.hibernate package.
Instance of SessionFactory can be achieved by using buildSessionFactory()
method of Configuration class.
SessionFactory can be used to hold database connection.
SessionFactory is thread-safe.
SessionFactory is an immutable object.
SessionFactory sf = con.buildSessionFactory();
Session (Hibernate)
Session is an interface, which is located in org.hibernate package.
Instance of Session can be achieved by using openSession() or
getCurrentSession() method of SessionFactory .
openSession() method returns a new instance of Session .
getCurrentSession() method returns existing instance of Session .
By using Session , we can perform CRUD operations.
Session provides methods like save() , delete() , update() , get() etc.
Session is thread-unsafe.
Session is a mutable object.
e.g.
Session session = sf.openSession();
Transaction (Hibernate)
Transaction is an interface, which is located in org.hibernate package.
Instance of Transaction can be achieved by using getTransaction() or
beginTransaction() methods of the Session interface.
getTransaction() method returns existing Transaction.
beginTransaction() method returns a new instance of Transaction.
Transaction must commit the changes made by the Session.
Transaction tx = session.beginTransaction();
Employee e = new Employee();
e.setName("sagar mehta");
e.setCompany("tcs");
e.setDesignation("ui developer");
e.setSalary(12000);
session.save(e);
tx.commit();
State of Objects in Hibernate
1) Transient State
In Hibernate, an object is considered in transient state during object creation.
Transient object is also considered as a new object.
2) Persistence State
In Hibernate, an object is considered in persistence state if it is associated with a
session but not yet saved in the database.
Persistence object is also considered as a processing object.
3) Detached State
In Hibernate, an object is considered in detached state if it is no longer associated with
the session but still linked to the database record.
Detached object is also considered as an old object.
Methods of Session in Hibernate
1) save()
save() method can be used to insert a record.
save() method requires a transient object.
save() method returns Serializable ID.
2) delete()
delete() method can be used to delete a record.
delete() method requires a detached object.
3) get()
get() method can be used to fetch a record.
get() method returns the object or null if the record is not found.
4) load()
load() method can be used to fetch a record.
load() method returns the object or throws an exception if the record is not found.
5) update()
update() method can be used to update record.
update() method requires detached object.
6) saveOrUpdate()
saveOrUpdate() method can be used to insert or update a record.
saveOrUpdate() method inserts a record if mentioned object is transient.
saveOrUpdate() method updates a record if mentioned object is detached.
JPA API
JPA stands for javax persistence API.
It is a specification regarding object mapping.
By using JPA annotation, we don't have to create & maintain separate hbm.xml file.
1) @Entity
@Entity is an annotation, which is located in javax.persistence package.
This annotation can be used to denote a class as an entity.
This annotation can be used over class name.
2) @Id
@Id is an annotation, which is located in javax.persistence package.
This annotation can be used to denote property as a primary key.
This annotation can be used over property name.
3) @GeneratedValue
@GeneratedValue is an annotation, which is located in javax.persistence package.
This annotation can be used to denote generation type of ID.
This annotation can be used over property name.
4 @Table
is an annotation, which is located in javax.persistence package.
@Table annotation can be used to specify class as a user-defined table.
This annotation can be used over class name.
5) @Column
@Column is an annotation, which is located in javax.persistence package.
@Table annotation can be used to specify property as a user-defined column.
This annotation can be used over the property name.
6) @Transient
@Transient is an annotation, which is located in javax.persistence package.
This annotation can be used to denote a property as a transient property.
In Hibernate, a transient property will not be a part of the Session anymore.
7) @Embeddable
- @Embeddable is an annotation, which is located in javax.persistence package.
This annotation can be used to denote a class as an embeddable class.
In Hibernate, an embeddable class will not create a separate table; it becomes a part of
the existing table.
This annotation can be used over the class name.
8) @Embedded
- @Embedded is an annotation, which is located in javax.persistence package.
This annotation can be used to denote a property as an embedded property.
Property of an embeddable class is considered as an embedded property.
This annotation can be used over the property name.
import javax.persistence.*;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String designation;
private String company;
@Column(columnDefinition = "double(10,2)")
private double salary;
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", designation=" +
designation + ", salary=" + salary + "]";
}
}
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.Properties;
public class HBUtils {
public static SessionFactory sf = new Configuration()
.setProperties(p1())
.addAnnotatedClass(Employee.class)
.buildSessionFactory();
private static Properties p1() {
Properties p = new Properties();
p.setProperty("hibernate.connection.driver_class",
"com.mysql.cj.jdbc.Driver");
p.setProperty("hibernate.connection.url",
"jdbc:mysql://localhost:3306/jap78");
p.setProperty("hibernate.connection.username", "root");
p.setProperty("hibernate.connection.password", "root");
p.setProperty("hibernate.dialect",
"org.hibernate.dialect.MySQL8Dialect");
p.setProperty("hibernate.hbm2ddl.auto", "update");
p.setProperty("hibernate.show_sql", "true");
p.setProperty("hibernate.format_sql", "true");
return p;
}
}