3. Hibernate was developed in 2001 by Gavin king (Australian
Developer) with his colleagues from Circus Technologies.
ORM Tool.
Used in data layer of Applications
Implement JPA
The main aim was to provide better persistence capabilities than those of EJB2.
3
INTRODUCTION
12/13/2021
4. it is Java framework that simplifies the interaction of java programming with
database.
it is open source , light weight, ORM(Object Relationship Mapping) Tool.
Implement JPA
Advantages
Open source and Lightweight
Fast performance(2 level cache)
HQL –Database Independent queries
Automatic Table Creation
Simplifies Joins
4
Hibernate Framework
12/13/2021
5. • 2001: The first version of Hibernate was released. The main aim was to provide
better persistence capabilities than those of EJB2, by reducing complexities and
adding some missing features.
• 2003: The new version of Hibernate was launched that is hibernate2, which
provides many improvements over the first version.
• 2005: The third version of Hibernate was released known as hibernate 3.0 with
some new key features. Some features are an interceptor, user-defined filters,
and Annotations of JDK 5.0.
• 2010: Hibernate 3 (version 3.5 and up) has become a certified implementation of
the JPA 2.0 specification.
• 2011: The new version of Hibernate was released known as Hibernate 4.0.0 with
some new features such as support, multi-tenancy, better session opening, and
many more.
5
History
12/13/2021
6. • 2012: Another version of Hibernate was released known as Hibernate ORM 4.1.9.
• 2013: New version Hibernate ORM 4.2 Final was released in March 2013. New
version Hibernate ORM 4.3.0 Final was released on December 2013 with a new
feature JPA 2.1.
• 2015: New version Hibernate ORM 5.0.2 Final was released on September 2015
with some improvements like bootstrapping, hibernate-java8, Karaf support, etc.
• 2017: In November 2017, Hibernate ORM 5.1.17 was released.
• 2018: New version Hibernate ORM 5.3 Final was released in October 2018.
• 2019: New version Hibernate ORM 5.4.0 Final was released in May 2019.
• 2021: Introducing new version ORM 5.5 Jakartha JPA
• 2021: Dropped support of Java assistance performance ORM 5.6
• 2021: Introducing the Performance tuning, Criteria, Type System ORM 6.0
6
History
12/13/2021
7. Hibernate supports for XML as well as JPA annotations
Hibernate provides a powerful query language(HQL) similar to SQL which is
object oriented and understands the concepts like inheritance, polymorphism and
association
it is open source project from the redhat community
it is easily integrated with any enterprise framework
it has lazy initialization mechanism and it will query on demand
It has cache mechanism to support performance
7
Benefits
12/13/2021
8. Hibernate code looks cleaner and readable than JDBC
Hibernate provides a powerful query language(HQL) similar to SQL which is
object oriented and understands the concepts like inheritance, polymorphism and
association which is not in JDBC
it implicitly provides Transaction Management where as in JDBC we have to
explicitly call out rollback and commit
In JDBC API are checked exception we have to write lot of try –catch block but
we don’t need to manage in Hibernate (unchecked exception)
HQL near to object oriented programming unless SQL
It supports annotations
8
Hibernate over JDBC
12/13/2021
9. Java Persistance API (JPA) provides a specification for managing the relational
data in applications. JPA specifications are defined with annotations in
a javax.persistence package. Using JPA annotation helps us in writing
implementation-independent code.
Hibernate uses JDBC for all database communications. It uses JDBC to interact
with the database.
9
Java Persistence API
12/13/2021
10. 10
Hibernate Architecture
12/13/2021
Configuration (org.hibernate.cfg.Configuration)It allows the application on startup, to
specify properties and mapping documents to be used when creating a SessionFactory.
Properties file contains database connection setup info while mapping specifies the classes
to be mapped.
SessionFactory (org.hibernate.SessionFactory)
It’s a thread-safe immutable object created per database & mainly used for creating
Sessions. It caches generated SQL statements and other mapping metadata that Hibernate
uses at runtime.
Session (org.hibernate.Session)
It’s a single-threaded object used to perform create, read, update and delete operations
for instances of mapped entity classes. Since it’s not thread-safe, it should not be long-
lived and each thread/transaction should obtain its own instance from a SessionFactory.
The Session object is lightweight and designed to be instantiated each time an interaction
is needed with the database. Persistent objects are saved and retrieved through a Session
object.
Transaction (org.hibernate.Transaction)
It’s a single-thread object used by the application to define units of work. A transaction is
associated with a Session. Transactions abstract application code from underlying
transaction implementations(JTA/JDBC), allowing the application to control transaction
boundaries via a consistent API. It’s an Optional API and application may choose not to use
it.
Query (org.hibernate.Query)
A single-thread object used to perform query on underlying database. A Session is a
factory for Query. Both HQL(Hibernate Query Language) & SQL can be used with Query
object.
15. 15
Sample Example: hibernate.cfg.xml
12/13/2021
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/college</property>
<property name="connection.username">postgres</property>
<property name="connection.password">admin</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
16. 16
Sample Example
12/13/2021
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="com.snipe.learning.hibernate.example.UserDetails"/>
</session-factory>
</hibernate-configuration>
17. 17
Sample Example:UserDetails
12/13/2021
package com.snipe.learning.hibernate.example;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class UserDetails {
@Id
private int userId;
private String name;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
18. 18
Sample Example
12/13/2021
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String password;
}
19. 19
Sample Example
12/13/2021
package com.snipe.learning.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.snipe.learning.hibernate.example.UserDetails;
public class TestHibernate {
public static void main(String[] args) {
UserDetails user =new UserDetails();
user.setUserId(1001);
user.setName("mallikarjuna");
user.setPassword("test");
// TODO Auto-generated method stub
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
20. 20
hbm2ddl Configuration and Name Annotations
12/13/2021
!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
package com.snipe.learning.hibernate.example;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity(name = "USER_DETAILS")
public class UserDetails {
@Id
@Column(name="user_id")
private int userId;
@Column(name="first_name")
private String name;
22. 22
Fetch Persisted data
12/13/2021
session = sessionFactory.openSession();
session.beginTransaction();
user = (UserDetails)session.get(UserDetails.class, 1);
System.out.println("data retireved::"+user.getUserId()+":"+user.getName());
session.getTransaction().commit();
session.close();
23. 23
Primary Key
12/13/2021
A surrogate key is a system generated (could be GUID, sequence, etc.) value with no
business meaning that is used to uniquely identify a record in a table.
Example : user_id, id so on
@Entity
@Table(name="Sample_Table")
public class UserDetails implements Serializable {
@Id
@Column(name="user_id")
@GeneratedValue
private int userId;
… }
@GeneratedValue(strategy=GenerationType.AUTO ) {Auto, identity, sequence, table)
private int userId;
A natural key is a column or set of columns that already exist in the table (e.g. they
are attributes of the entity within the data model) and uniquely identify a record in
the table. Since these columns are attributes of the entity they obviously have
business meaning.
Example : SSN or emailed or phone no in employee table
24. 24
Value Types and Embedded Objects
12/13/2021
@Entity
@Table(name="emp")
public class Employee {
@Id
private int id;
private String name;
@Embedded
private Dept dept; // indicate Dept fields are embeded as a component in emp table
private String phoneno;
….
}
@Embeddable // it works like independent component ready to embeded in other table as value
public class Dept {
private int deptno;
private String dname;
private String location;
….}
25. 25
Attribute overrides and Embedded Object keys
12/13/2021
AttributeOverride indicate to ignore the what value column has and enforcing to override the latest specified value.
Multiple column can be overridden through plural of AttributeOverrides.
@Entity
@Table(name="employeeao")
public class EmployeeAO {
@Id
private int id;
private String name;
@Embedded
private Dept dept;
private String phoneno;
@Embedded
@AttributeOverrides({
@AttributeOverride(name="doorno",column=@Column(name="home_doorno")),
@AttributeOverride(name="city", column=@Column(name="home_city")),
@AttributeOverride(name="location", column=@Column(name="home_location"))
})
private AddressAO home_address;
@Embedded
@AttributeOverrides({
@AttributeOverride(name="doorno",column=@Column(name="office_doorno")),
@AttributeOverride(name="city", column=@Column(name="office_city")),
@AttributeOverride(name="location", column=@Column(name="office_location"))
})
private AddressAO office_address;
26. 26
Attribute overrides and Embedded Object keys
12/13/2021
When you want to use all the member variables are uniquely identified as primary
key then object key can be used rather as key @Id.
FOR Example : @EmbeddedId
private Dept dept;
27. 27
Configuring Collections
12/13/2021
Building a separate table linking to the existing table with reference links through elementcollections
For instance company has branches in many locations. Then branches can be elementcollection to save many
branches mapping to primary id of company.
company
@Entity
@Table(name="company")
public class Company {
@Id
@Column(name="comp_code")
@GeneratedValue(strategy = GenerationType.AUTO)
private int code;
private String cname;
@ElementCollection
private Set<Branch> branches= new HashSet<Branch>();
….}
@Embeddable
public class Branch {
private String code;
private String name;
private String location;
…}
29. 29
Configuring Collections-adding primary key
12/13/2021
Incase you want to have the primary key in the extended table like branches we should have CollectionId should be used
with along Generator of the key.
The sample code snippet as below
import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
@ElementCollection
@JoinTable(name="comp2_branch",joinColumns =@JoinColumn(name="cbrid"))
@GenericGenerator(name="sequence-gen", strategy="sequence")
@CollectionId(columns = @Column(name="branch_id"), generator = "sequence", type = @Type(type="long"))
private Collection<Branch> branches= new ArrayList<Branch>();
30. 30
–Proxy Objects, Eager and Lazy fetch
12/13/2021
Eager Loading is a design pattern in which data initialization occurs on the spot
Lazy Loading is a design pattern which is used to defer initialization of an object as long as it's possible
@Entity
@Table(name="company3_detail")
public class Company3 {
@Id
@Column(name="comp_code")
@GeneratedValue(strategy = GenerationType.AUTO)
private int code;
private String cname;
@ElementCollection(fetch = FetchType.EAGER)
@JoinTable(name="comp3_branch",joinColumns =@JoinColumn(name="cbrid"))
@GenericGenerator(name="sequence-gen", strategy="sequence")
@CollectionId(columns = @Column(name="branch_id"), generator = "sequence", type = @Type(type="long"))
private Collection<Branch> branches= new ArrayList<Branch>();
Test loading
company = null;
session = sessionFactory.openSession();
company = (Company3)session.get(Company3.class, 1);
System.out.println(company.getCode() + " "+company.getCname());
System.out.println(company.getBranches().size());
session.close();
31. 31
Mapping – one to one
12/13/2021
The association of one table to another. It means one object linked only one object.
For instance one employee works in one department.
EmployeeOO
@Entity
@Table(name="EmpOO")
public class EmployeeOO {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int empno;
private String ename;
private String mobileno;
private String designation;
@OneToOne
@JoinColumn(name="dept_id")
private DeptOO dept;
..}
DeptOO
@Entity
public class DeptOO {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int deptId;
private String dname;
private String dloc;
32. 32
Mapping – one to one
12/13/2021
TestOneToOneExample
EmployeeOO employee =new EmployeeOO();
DeptOO dept= new DeptOO();
employee.setEname("Mallikarjuna");
employee.setDesignation("Trainer");
employee.setMobileno("9739301041");
dept.setDname("IT Education");
dept.setDloc("Mysuru");
employee.setDept(dept);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(employee);
session.save(dept);
session.getTransaction().commit();
session.close();
Queries Generated
Hibernate: insert into EmpOO (dept_id, designation, ename, mobileno, empno) values (?, ?, ?, ?, ?)
Hibernate: insert into DeptOO (dloc, dname, deptId) values (?, ?, ?)
Hibernate: update EmpOO set dept_id=?, designation=?, ename=?, mobileno=? where empno=?
33. 33
Mapping – one to many
12/13/2021
Mapping one objects to many other objects through one-to-many relationships. This will be done through annotation
@OneToMany.
EmpoyeeOM
@Entity
public class EmployeeOM {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int empno;
private String ename;
private String mobileno;
private String designation;
@OneToMany
@JoinTable(name = "emp_dept", joinColumns = @JoinColumn(name = "emp_id"), inverseJoinColumns = @JoinColumn(name =
"dept_id"))
private Collection<DeptOM> dept = new ArrayList<DeptOM>();
..
}
DeptOM
@Entity
public class DeptOM {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int deptId;
private String dname;
private String dloc;
@ManyToOne
private EmployeeOM emp; ..}
34. 34
Mapping – one to many
12/13/2021
Hibernate.cfg.xml
<mapping class="com.snipe.learning.hibernate.example.EmployeeOM" />
<mapping class="com.snipe.learning.hibernate.example.DeptOM" />
TestOneToManyExample
EmployeeOM emp = new EmployeeOM();
emp.setEname("Mallikarjuna");
emp.setDesignation("Trainer");
emp.setMobileno("9739201041");
DeptOM dept = new DeptOM();
dept.setDname("physics");
dept.setDloc("mysuru");
dept.setEmp(emp);
DeptOM dept1 = new DeptOM();
dept1.setDname("chemistry");
dept1.setDloc("mysuru");
dept1.setEmp(emp);
emp.getDept().add(dept);
emp.getDept().add(dept1);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(emp);
session.save(dept);
session.save(dept1);
session.getTransaction().commit();
35. 35
Mapping – one to many
12/13/2021
Generated Queries
Hibernate: insert into EmployeeOM (designation, ename, mobileno, empno) values (?, ?, ?, ?)
Hibernate: insert into DeptOM (dloc, dname, emp_empno, deptId) values (?, ?, ?, ?)
Hibernate: insert into DeptOM (dloc, dname, emp_empno, deptId) values (?, ?, ?, ?)
Hibernate: insert into emp_dept (emp_id, dept_id) values (?, ?)
Hibernate: insert into emp_dept (emp_id, dept_id) values (?, ?)
36. 36
Mapping – many to many
12/13/2021
Mapping many objects to many other objects through many-to-many relationships. This will be done
through annotation similar to other mapping
EmployeeMM
@Entity
public class EmployeeMM {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int empid;
private String name;
private String email;
@ManyToMany
@JoinTable(name = "empmm_deptmm", joinColumns = @JoinColumn(name = "emp_id"), inverseJoinColumns = @JoinColumn(name =
"dept_id"))
private Collection<DeptMM> dept = new ArrayList<DeptMM>();
..}
DeptMM
@Entity
public class DeptMM {
@Id
@GeneratedValue
private int dno;
private String dname;
private String dloc;
@ManyToMany(mappedBy = "dept")
private Collection<EmployeeMM> employee = new ArrayList<EmployeeMM>();
37. 37
Mapping – many to many
12/13/2021
Mapping many objects to many other objects through many-to-many relationships. This will be done
through annotation similar to other mapping
EmployeeMM emp1 = new EmployeeMM();
emp1.setName("Mallikarjuna");
emp1.setEmail("Trainer");
DeptMM dept1 = new DeptMM();
dept1.setDname("physics");
dept1.setDloc("mysuru");
DeptMM dept2 = new DeptMM();
dept2.setDname("physics");
dept2.setDloc("mysuru");
emp1.getDept().add(dept1);
emp1.getDept().add(dept2);
dept1.getEmployee().add(emp1);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(emp1);
session.save(dept1);
session.save(dept2);
session.getTransaction().commit();
38. 38
Mapping – many to many
12/13/2021
Mapping many objects to many other objects through many-to-many relationships. This will be done
through annotation similar to other mapping
Hibernate: insert into EmployeeMM (email, name, empid) values (?, ?, ?)
Hibernate: insert into DeptMM (dloc, dname, dno) values (?, ?, ?)
Hibernate: insert into DeptMM (dloc, dname, dno) values (?, ?, ?)
Hibernate: insert into empmm_deptmm (emp_id, dept_id) values (?, ?)
Hibernate: insert into empmm_deptmm (emp_id, dept_id) values (?, ?)
40. 40
Inhertiance
12/13/2021
Relational databases don't have a straightforward way to map class hierarchies onto database
tables.To address this, the JPA specification provides several strategies:
•MappedSuperclass – the parent classes, can't be entities
•Single Table – The entities from different classes with a common ancestor are placed in a
single table.
•Table per Class – All the properties of a class are in its table, so no join is required.
Each strategy results in a different database structure.
Joined Table – Each class has its table, and querying a subclass entity requires joining the
tables.
Entity inheritance means that we can use polymorphic queries for retrieving all the subclass
entities when querying for a superclass.
Since Hibernate is a JPA implementation, it contains all of the above as well as a few
Hibernate-specific features related to inheritance.
51. 51
Transient, Persistent and Detached objects
12/13/2021
UserTPD
@Entity
public class UserTPD {
@Id
private int id;
private String name;
..}
TestUserTPD
UserTPD user = new UserTPD();
user.setName("Trainsient Object");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
user.setName("In session:: Persistent Object");
user.setName("In session:: Latest Persistent Object");
session.getTransaction().commit();
session.close();
user.setName("After Session :: Detached Object");
52. 52
Hibernate Query Language(HQL)
12/13/2021
• Hibernate Query Language (HQL) is an object-oriented query language
• It is similar to SQL, but instead of operating on tables and columns, HQL works with
persistent objects and their properties.
• HQL queries are translated by Hibernate into conventional SQL queries, which in turns
perform action on database.
• Advantages::
• Database Independent
• Easily can be learned
53. 53
Hibernate Query Language(HQL)
12/13/2021
UserHQL
@Entity
public class UserHQL {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
..}
SampleHQLExample1
UserHQL userHQL = null;
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
for (int count = 0; count <= 10; count++) {
userHQL = new UserHQL();userHQL.setName("USER" + count);session.save(userHQL);
}
session.getTransaction().commit(); session.close();
sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession(); session.beginTransaction();
@SuppressWarnings("unchecked")
TypedQuery<UserHQL> query = session.createQuery("from UserHQL");
List<UserHQL> users = query.getResultList();session.getTransaction().commit();session.close();
for (UserHQL user : users) {
System.out.println("user::" + user.getName());
}
55. 55
HQL:Update and delete
12/13/2021
SampleHQLUpdate : update
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
TypedQuery<UserHQL> query = session.createQuery("Update UserHQL set name=:iname where id=40");
query.setParameter("iname", "swamy");
int status = query.executeUpdate();
session.getTransaction().commit();
session.close();
SampleHQLDelete : delete
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
TypedQuery<UserHQL> query = session.createQuery("delete from UserHQL where id=40");
int status = query.executeUpdate();
session.getTransaction().commit();
session.close();
56. 56
HQL:Named Query
12/13/2021
A major disadvantage of having HQL and SQL scattered across data access objects is that it
makes the code unreadable. Hence, it might make sense to group all HQL and SQL in one place and
use only their reference in the actual data access code. Fortunately, Hibernate allows us to do
this with named queries.
A named query is a statically defined query with a predefined unchangeable query string.
They're validated when the session factory is created, thus making the application to fail fast
in case of an error.
@NamedQueries(
{
@NamedQuery(
name = "findUserByName",
query = "from UserHQL user where user.name = :name"
)
}
)
@Entity
public class UserHQL {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
..}
57. 57
HQL:Named Query
12/13/2021
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
TypedQuery<UserHQL> query = session.getNamedQuery("findUserByName");
query.setParameter("name","Mallikarjuna");
List<UserHQL> user = query.getResultList();
System.out.println(user.get(0).getName());
session.getTransaction().commit();
session.close();
Output
Hibernate: select userhql0_.id as id1_20_, userhql0_.name as name2_20_ from UserHQL userhql0_ where userhql0_.name=?
Mallikarjuna
58. 58
HQL:Criteria API
12/13/2021
It enables us to write queries without doing raw SQL as well as gives us some object-oriented
control over the queries, which is one of the main features of Hibernate. The Criteria API
allows us to build up a criteria query object programmatically, where we can apply different
kinds of filtration rules and logical conditions.
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(UserHQL.class);
criteria.add(Restrictions.eq("name", "Mallikarjuna"));
List<UserHQL> results = criteria.list();
System.out.println("Results.size::"+results.size() + "name::results"+results.get(0).getName());
session.getTransaction().commit();
session.close();
Output
Results.size::21 name::results Mallikarjuna
59. 59
HQL:Criteria API
12/13/2021
Sample example :ON Employeee class
Criteria criteria = session.createCriteria(Employee.class)
Records having salary more than 10000 - criteria.add(Restrictions.gt("salary", 10000));
Records having salary less than 10000 - criteria.add(Restrictions.lt("salary", 10000));
Records having fistName starting with Malli - criteria.add(Restrictions.like("firstName", “Malli%"));
Case sensitive form of the restriction. - criteria.add(Restrictions.ilike("firstName", “Malli%"));
Records having salary in between 10000 and 50000 - criteria.add(Restrictions.between("salary", 10000, 50000));
To check if the given property is null - criteria.add(Restrictions.isNull("salary"));
To check if the given property is not null - criteria.add(Restrictions.isNotNull("salary"));
To check if the given property is empty - criteria.add(Restrictions.isEmpty("salary"));
To check if the given property is not empty - criteria.add(Restrictions.isNotEmpty("salary"));
60. 60
Criteria API-Logical Expressions
12/13/2021
Sample example :ON Employeee class
Criteria criteria = session.createCriteria(Employee.class)
Criterion salary = Restrictions.gt("salary", 10000);
Criterion name = Restrictions.ilike("firstName","Mallik%");
// To get records matching with OR conditions
LogicalExpression orExp = Restrictions.or(salary, name);
criteria.add( orExp );
// To get records matching with AND conditions
LogicalExpression andExp = Restrictions.and(salary, name);
criteria.add( andExp );
List results = criteria.list();
Pagination :
Criteria criteria = session.createCriteria(Employee.class);
criteria .setFirstResult(1);
criteria .setMaxResults(10);
List results = cr.list();
61. 61
Projections and Aggregations
12/13/2021
Sample example :ON Employeee class
Criteria criteria = session.createCriteria(Employee.class)
// To get total row count.
criteria.setProjection(Projections.rowCount());
// To get average of a property.
criteria.setProjection(Projections.avg("salary"));
// To get distinct count of a property.
criteria.setProjection(Projections.countDistinct("firstName"));
// To get maximum of a property.
criteria.setProjection(Projections.max("salary"));
// To get minimum of a property.
criteria.setProjection(Projections.min("salary"));
// To get sum of a property.
criteria.setProjection(Projections.sum("salary"));
62. 62
Caching
12/13/2021
Caching is a mechanism to enhance the performance of the system. It is actually buffers the
data in memory in application and database. It avoids the database hits which inturn improve
the performance.
63. 63
Caching
12/13/2021
CACHE LEVEL DESCRIPTION
First Level Cache The first-level cache is the Session cache and is a mandatory cache
through which all requests must pass.
The Session object is under its own cache before committing it to the
database.
The update queries always monitored and explicit database call happens
only if required
This cache will be lost once session closed
Second Level Cache This is across session and application in the context cache maintained
before call to the database
It is optional and which is explicitly configured using the third-party
cache provider.
Querly Level Cache This implements for the query resultsets and it is integrated with
secondlevel cache
This is useful for the queries runs frequently with the same parameters
64. 64
Caching
12/13/2021
CONCURRENCY STRATEGIES DESCRIPTION
Transactional Most likely used in read data and rare update
Read-write Most likely used in read and write data
Nonstrict-read-write Data is not critical concern
Read-only It uses for reference data only no modification
CACHE NAME DESCRIPTION
EHCache It can cache in memory or on disk and clustered
caching
OSCache caching to memory and disk in a single JVM with a
rich set of expiration policies and query cache
support.
warmCache It uses clustered invalidation, but doesn't support
the Hibernate query cache.