SlideShare une entreprise Scribd logo
1  sur  66
13 December 2021 1
Hibernate
Name :: Mallikarjuna G D
Reach me @ Training ::
Email :: gdmallikarjuna@gmail.com
2
CONTENTS
12/13/2021
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
 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
• 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
• 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
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
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
 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
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.
11
CHALLENGES
12/13/2021
• Member variables to columns
• Represent ISA and HAS-A relationships
• Handling datatypes
• Object Modifications
12
HIBERNATE CONFIGURATION
12/13/2021
13
HIBERNATE CONFIGURATION
12/13/2021
14
Sample Example
12/13/2021
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
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
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
Sample Example
12/13/2021
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String password;
}
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
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;
21
More Annotations
12/13/2021
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
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
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
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
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
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;
…}
28
Configuring Collections
12/13/2021
Company company = new Company();
Branch branch =new Branch();
company.setCode(1001);
company.setCname("SNI");
Set<Branch> branches = new HashSet<Branch>();
//BRANCH 1
branch.setCode("c1001");
branch.setName("basaveshwara nagara");
branch.setLocation("BNAGARA");
branches.add(branch);
//BRANCH 2
branch =new Branch();
branch.setCode("c1002");
branch.setName("Rajarajeshwari nagara");
branch.setLocation("RRNAGARA");
branches.add(branch);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(company);
session.getTransaction().commit();
session.close();
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
–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
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
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
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
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
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
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
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
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 (?, ?)
39
Mapping – NOTFOUND & CASCADE
12/13/2021
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.
41
Inhertiance
12/13/2021
42
Inheritance: Default
12/13/2021
Person_Info
@Entity
public class Person_Info {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String age;
private String sex;
private String address;..
}
EmployeeI
@Entity
public class EmployeeI extends Person_Info {
private int empid;
private String exp;
private String empType;
..}
Student
@Entity
public class Student extends Person_Info {
private String rollNum;
private String degree;
..}
Default insertions:
Hibernate: insert into Person_Info (address, age, name, sex,
DTYPE, id) values (?, ?, ?, ?, 'Person_Info', ?)
Hibernate: insert into Person_Info (address, age, name, sex,
empType, empid, exp, DTYPE, id) values (?, ?, ?, ?, ?, ?, ?,
'EmployeeI', ?)
Hibernate: insert into Person_Info (address, age, name, sex,
degree, rollNum, DTYPE, id) values (?, ?, ?, ?, ?, ?,
'Student', ?)
43
Inheritance: Default
12/13/2021
// TODO Auto-generated method stub
Person_Info person = new Person_Info();
person.setName("Mallikarjuna");
person.setAge("100");
person.setAddress("Mysuru");
person.setSex("Male");
EmployeeI emp = new EmployeeI();
emp.setEmpType("Driver");
emp.setExp("12");
emp.setEmpid(1001);
Student student =new Student();
student.setRollNum("1002");
student.setDegree("BSC");
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(person);
session.save(emp);
session.save(student);
session.getTransaction().commit();
Default insertions:
Hibernate: insert into Person_Info (address, age, name, sex,
DTYPE, id) values (?, ?, ?, ?, 'Person_Info', ?)
Hibernate: insert into Person_Info (address, age, name, sex,
empType, empid, exp, DTYPE, id) values (?, ?, ?, ?, ?, ?, ?,
'EmployeeI', ?)
Hibernate: insert into Person_Info (address, age, name, sex,
degree, rollNum, DTYPE, id) values (?, ?, ?, ?, ?, ?,
'Student', ?)
44
Inheritance: MappedSuperClass
12/13/2021
Person_Info
@MappedSuperclass
public class Person_Info {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String age;
private String sex;
private String address;..
}
EmployeeI
@Entity
public class EmployeeI extends Person_Info {
private int empid;
private String exp;
private String empType;
..}
Student
@Entity
public class Student extends Person_Info {
private String rollNum;
private String degree;
..}
Default insertions:
Hibernate: insert into Person_Info (address, age, name, sex,
DTYPE, id) values (?, ?, ?, ?, 'Person_Info', ?)
Hibernate: insert into Person_Info (address, age, name, sex,
empType, empid, exp, DTYPE, id) values (?, ?, ?, ?, ?, ?, ?,
'EmployeeI', ?)
Hibernate: insert into Person_Info (address, age, name, sex,
degree, rollNum, DTYPE, id) values (?, ?, ?, ?, ?, ?,
'Student', ?)
45
Inheritance: MappedSuperClass
12/13/2021
// TODO Auto-generated method stub
Person_Info person = new Person_Info();
person.setName("Mallikarjuna");
person.setAge("100");
person.setAddress("Mysuru");
person.setSex("Male");
EmployeeI emp = new EmployeeI();
emp.setEmpType("Driver");
emp.setExp("12");
emp.setEmpid(1001);
Student student =new Student();
student.setRollNum("1002");
student.setDegree("BSC");
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(emp);
session.save(student);
session.getTransaction().commit();
Default insertions:
Hibernate: insert into EmployeeI (address, age, name, sex,
empType, empid, exp, id) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into Student (address, age, name, sex,
degree, rollNum, id) values (?, ?, ?, ?, ?, ?, ?)
46
Inheritance: SingleTable strategy
12/13/2021
Person_InfoST
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE_PERSON",
discriminatorType = DiscriminatorType.STRING)
public class Person_InfoST {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String age;
private String sex;
private String address;
..}
EmployeeIST
@Entity
@DiscriminatorValue("EMP")
public class EmployeeIST extends Person_InfoST {
private int empid;
private String exp;
private String empType;..
}
StudentST
@Entity
@DiscriminatorValue("STD")
public class StudentST extends Person_InfoST {
private String rollNum;
private String degree; ..}
TestInheritanceSingleTable
Person_InfoST person = new Person_InfoST();
person.setName("Mallikarjuna");
person.setAge("100");
person.setAddress("Mysuru");
person.setSex("Male");
EmployeeIST emp = new EmployeeIST();
emp.setEmpType("Driver");
emp.setExp("12");
emp.setEmpid(1001);
StudentST student =new StudentST();
student.setRollNum("1002");
student.setDegree("BSC");
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(person);
session.save(emp);
session.save(student);
session.getTransaction().commit();
Hibernate: insert into Person_InfoST (address, age, name, sex,
TYPE_PERSON, id) values (?, ?, ?, ?, 'Person_InfoST', ?)
Hibernate: insert into Person_InfoST (address, age, name, sex,
empType, empid, exp, TYPE_PERSON, id) values (?, ?, ?, ?, ?, ?, ?,
'EMP', ?)
Hibernate: insert into Person_InfoST (address, age, name, sex, degree,
rollNum, TYPE_PERSON, id) values (?, ?, ?, ?, ?, ?, 'STD', ?)
47
Inheritance: Table Per class strategy
12/13/2021
Person_InfoTC
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person_InfoTC {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int pid;
private String name;
private String age;
private String sex;
private String address;..}
EmployeeTC
@Entity
public class EmployeeTC extends Person_InfoTC {
private int empid;
private String exp;
private String empType;
}
StudentTc
@Entity
public class StudentTC extends Person_InfoTC {
private String rollNum;
private String degree;
..}
TestInheritanceTPC
Person_InfoTC person = new Person_InfoTC();
person.setName("Mallikarjuna");
person.setAge("100");
person.setAddress("Mysuru");
person.setSex("Male");
EmployeeTC emp = new EmployeeTC();
emp.setEmpType("Driver");
emp.setExp("12");
emp.setEmpid(1001);
StudentTC student =new StudentTC();
student.setRollNum("1002");
student.setDegree("BSC");
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(person);
session.save(emp);
session.save(student);
session.getTransaction().commit();
48
Inheritance: JOIN strategy
12/13/2021
In this no repeated column present in the table
Person_InfoJS
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Person_InfoJS {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int pid;
private String name;
private String age;
private String sex;
private String address; …}
EmployeeJS
@Entity
public class EmployeeJS extends Person_InfoJS {
private int empid;
private String exp;
private String empType;..}
StudentJS
@Entity
public class StudentJS extends Person_InfoJS {
private String rollNum;
private String degree;..}
TestInheritanceJS
Person_InfoJS person = new Person_InfoJS();
person.setName("Mallikarjuna");
person.setAge("100");
person.setAddress("Mysuru");
person.setSex("Male");
EmployeeJS emp = new EmployeeJS();
emp.setEmpType("Driver");
emp.setExp("12");
emp.setEmpid(1001);
StudentJS student =new StudentJS();
student.setRollNum("1002");
student.setDegree("BSC");
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(person);
session.save(emp);
session.save(student);
session.getTransaction().commit();
49
CRUD
12/13/2021
@Entity
public class UserCRUD {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String location;
..}
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
for(int count=0;count<=10; count++) {
UserCRUD user =new UserCRUD();
user.setName("user"+count);
user.setLocation("place"+count);
session.save(user);
}
session.getTransaction().commit();
session.beginTransaction();
UserCRUD userCrud= session.get(UserCRUD.class, 5);
System.out.println("USERCRUD::"+userCrud.getId() +" :: "+userCrud.getName());
session.getTransaction().commit();
50
CRUD
12/13/2021
session.beginTransaction();
userCrud= session.get(UserCRUD.class, 6);
System.out.println("USERCRUD::"+userCrud.getId() +" :: "+userCrud.getName());
session.getTransaction().commit();
session.beginTransaction();
userCrud= session.get(UserCRUD.class, 7);
session.delete(userCrud);
System.out.println("USERCRUD::"+userCrud.getId() +" :: "+userCrud.getName());
session.getTransaction().commit();
session.beginTransaction();
userCrud= session.get(UserCRUD.class, 8);
userCrud.setName("Pranet");
session.update(userCrud);
System.out.println("USERCRUD::"+userCrud.getId() +" :: "+userCrud.getName());
session.getTransaction().commit();
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
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
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());
}
54
HQL:Pagination
12/13/2021
SampleHQLPagination
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
TypedQuery<UserHQL> query = session.createQuery("from UserHQL");
query.setFirstResult(6);
query.setMaxResults(5);
List<UserHQL> users = query.getResultList();
session.getTransaction().commit();
session.close();
for (UserHQL user : users) {
System.out.println("user::" + user.getName());
}
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
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
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
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
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
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
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
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
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
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.
65
References
12/13/2021
https://hibernate.org/
https://www.javatpoint.com/hibernate-tutorial
https://www.tutorialspoint.com/hibernate/
https://www.baeldung.com/learn-jpa-hibernate
THANK YOU
66
12/13/2021

Contenu connexe

Tendances

Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Java questions with answers
Java questions with answersJava questions with answers
Java questions with answersKuntal Bhowmick
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization Hitesh-Java
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot missMark Papis
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
Interview preparation net_asp_csharp
Interview preparation net_asp_csharpInterview preparation net_asp_csharp
Interview preparation net_asp_csharpMallikarjuna G D
 
Java interview questions
Java interview questionsJava interview questions
Java interview questionsSoba Arjun
 
50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutesArun Gupta
 
Project Presentation on Advance Java
Project Presentation on Advance JavaProject Presentation on Advance Java
Project Presentation on Advance JavaVikas Goyal
 

Tendances (20)

Servlet programming
Servlet programmingServlet programming
Servlet programming
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Angularj2.0
Angularj2.0Angularj2.0
Angularj2.0
 
Maven
MavenMaven
Maven
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
Hibernate3 q&a
Hibernate3 q&aHibernate3 q&a
Hibernate3 q&a
 
Java questions with answers
Java questions with answersJava questions with answers
Java questions with answers
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Hibernate notes
Hibernate notesHibernate notes
Hibernate notes
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Interview preparation net_asp_csharp
Interview preparation net_asp_csharpInterview preparation net_asp_csharp
Interview preparation net_asp_csharp
 
Connection Pooling
Connection PoolingConnection Pooling
Connection Pooling
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes
 
Hibernate Advance Interview Questions
Hibernate Advance Interview QuestionsHibernate Advance Interview Questions
Hibernate Advance Interview Questions
 
Project Presentation on Advance Java
Project Presentation on Advance JavaProject Presentation on Advance Java
Project Presentation on Advance Java
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 

Similaire à Hibernate

Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview QuestionsMayank Kumar
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3Oracle
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggetsVirtual Nuggets
 
Content Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitContent Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitJukka Zitting
 
Hibernate
HibernateHibernate
HibernateAjay K
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tooljavaease
 
Hibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersHibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersAnuragMourya8
 
Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1PawanMM
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Trainingsourabh aggarwal
 

Similaire à Hibernate (20)

Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3
 
Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate 18052012
Hibernate 18052012Hibernate 18052012
Hibernate 18052012
 
Content Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitContent Storage With Apache Jackrabbit
Content Storage With Apache Jackrabbit
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Hibernate
HibernateHibernate
Hibernate
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
 
Hibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersHibernate Interview Questions and Answers
Hibernate Interview Questions and Answers
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 

Plus de Mallikarjuna G D (20)

Reactjs
ReactjsReactjs
Reactjs
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
 
CSS
CSSCSS
CSS
 
Angular 2.0
Angular  2.0Angular  2.0
Angular 2.0
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
 
Mmg logistics edu-final
Mmg  logistics edu-finalMmg  logistics edu-final
Mmg logistics edu-final
 
Interview preparation devops
Interview preparation devopsInterview preparation devops
Interview preparation devops
 
Interview preparation testing
Interview preparation testingInterview preparation testing
Interview preparation testing
 
Interview preparation data_science
Interview preparation data_scienceInterview preparation data_science
Interview preparation data_science
 
Interview preparation full_stack_java
Interview preparation full_stack_javaInterview preparation full_stack_java
Interview preparation full_stack_java
 
Enterprunership
EnterprunershipEnterprunership
Enterprunership
 
Core java
Core javaCore java
Core java
 
Type script
Type scriptType script
Type script
 
Git Overview
Git OverviewGit Overview
Git Overview
 
Jenkins
JenkinsJenkins
Jenkins
 
Hadoop
HadoopHadoop
Hadoop
 
Digital marketing
Digital marketingDigital marketing
Digital marketing
 
Training
TrainingTraining
Training
 
Project excursion career_orientation
Project excursion career_orientationProject excursion career_orientation
Project excursion career_orientation
 
Installer benchmarking
Installer benchmarkingInstaller benchmarking
Installer benchmarking
 

Dernier

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Dernier (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 

Hibernate

  • 1. 13 December 2021 1 Hibernate Name :: Mallikarjuna G D Reach me @ Training :: Email :: gdmallikarjuna@gmail.com
  • 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.
  • 11. 11 CHALLENGES 12/13/2021 • Member variables to columns • Represent ISA and HAS-A relationships • Handling datatypes • Object Modifications
  • 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; …}
  • 28. 28 Configuring Collections 12/13/2021 Company company = new Company(); Branch branch =new Branch(); company.setCode(1001); company.setCname("SNI"); Set<Branch> branches = new HashSet<Branch>(); //BRANCH 1 branch.setCode("c1001"); branch.setName("basaveshwara nagara"); branch.setLocation("BNAGARA"); branches.add(branch); //BRANCH 2 branch =new Branch(); branch.setCode("c1002"); branch.setName("Rajarajeshwari nagara"); branch.setLocation("RRNAGARA"); branches.add(branch); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(company); session.getTransaction().commit(); session.close();
  • 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 (?, ?)
  • 39. 39 Mapping – NOTFOUND & CASCADE 12/13/2021
  • 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.
  • 42. 42 Inheritance: Default 12/13/2021 Person_Info @Entity public class Person_Info { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; private String age; private String sex; private String address;.. } EmployeeI @Entity public class EmployeeI extends Person_Info { private int empid; private String exp; private String empType; ..} Student @Entity public class Student extends Person_Info { private String rollNum; private String degree; ..} Default insertions: Hibernate: insert into Person_Info (address, age, name, sex, DTYPE, id) values (?, ?, ?, ?, 'Person_Info', ?) Hibernate: insert into Person_Info (address, age, name, sex, empType, empid, exp, DTYPE, id) values (?, ?, ?, ?, ?, ?, ?, 'EmployeeI', ?) Hibernate: insert into Person_Info (address, age, name, sex, degree, rollNum, DTYPE, id) values (?, ?, ?, ?, ?, ?, 'Student', ?)
  • 43. 43 Inheritance: Default 12/13/2021 // TODO Auto-generated method stub Person_Info person = new Person_Info(); person.setName("Mallikarjuna"); person.setAge("100"); person.setAddress("Mysuru"); person.setSex("Male"); EmployeeI emp = new EmployeeI(); emp.setEmpType("Driver"); emp.setExp("12"); emp.setEmpid(1001); Student student =new Student(); student.setRollNum("1002"); student.setDegree("BSC"); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(person); session.save(emp); session.save(student); session.getTransaction().commit(); Default insertions: Hibernate: insert into Person_Info (address, age, name, sex, DTYPE, id) values (?, ?, ?, ?, 'Person_Info', ?) Hibernate: insert into Person_Info (address, age, name, sex, empType, empid, exp, DTYPE, id) values (?, ?, ?, ?, ?, ?, ?, 'EmployeeI', ?) Hibernate: insert into Person_Info (address, age, name, sex, degree, rollNum, DTYPE, id) values (?, ?, ?, ?, ?, ?, 'Student', ?)
  • 44. 44 Inheritance: MappedSuperClass 12/13/2021 Person_Info @MappedSuperclass public class Person_Info { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; private String age; private String sex; private String address;.. } EmployeeI @Entity public class EmployeeI extends Person_Info { private int empid; private String exp; private String empType; ..} Student @Entity public class Student extends Person_Info { private String rollNum; private String degree; ..} Default insertions: Hibernate: insert into Person_Info (address, age, name, sex, DTYPE, id) values (?, ?, ?, ?, 'Person_Info', ?) Hibernate: insert into Person_Info (address, age, name, sex, empType, empid, exp, DTYPE, id) values (?, ?, ?, ?, ?, ?, ?, 'EmployeeI', ?) Hibernate: insert into Person_Info (address, age, name, sex, degree, rollNum, DTYPE, id) values (?, ?, ?, ?, ?, ?, 'Student', ?)
  • 45. 45 Inheritance: MappedSuperClass 12/13/2021 // TODO Auto-generated method stub Person_Info person = new Person_Info(); person.setName("Mallikarjuna"); person.setAge("100"); person.setAddress("Mysuru"); person.setSex("Male"); EmployeeI emp = new EmployeeI(); emp.setEmpType("Driver"); emp.setExp("12"); emp.setEmpid(1001); Student student =new Student(); student.setRollNum("1002"); student.setDegree("BSC"); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(emp); session.save(student); session.getTransaction().commit(); Default insertions: Hibernate: insert into EmployeeI (address, age, name, sex, empType, empid, exp, id) values (?, ?, ?, ?, ?, ?, ?, ?) Hibernate: insert into Student (address, age, name, sex, degree, rollNum, id) values (?, ?, ?, ?, ?, ?, ?)
  • 46. 46 Inheritance: SingleTable strategy 12/13/2021 Person_InfoST @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="TYPE_PERSON", discriminatorType = DiscriminatorType.STRING) public class Person_InfoST { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; private String age; private String sex; private String address; ..} EmployeeIST @Entity @DiscriminatorValue("EMP") public class EmployeeIST extends Person_InfoST { private int empid; private String exp; private String empType;.. } StudentST @Entity @DiscriminatorValue("STD") public class StudentST extends Person_InfoST { private String rollNum; private String degree; ..} TestInheritanceSingleTable Person_InfoST person = new Person_InfoST(); person.setName("Mallikarjuna"); person.setAge("100"); person.setAddress("Mysuru"); person.setSex("Male"); EmployeeIST emp = new EmployeeIST(); emp.setEmpType("Driver"); emp.setExp("12"); emp.setEmpid(1001); StudentST student =new StudentST(); student.setRollNum("1002"); student.setDegree("BSC"); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(person); session.save(emp); session.save(student); session.getTransaction().commit(); Hibernate: insert into Person_InfoST (address, age, name, sex, TYPE_PERSON, id) values (?, ?, ?, ?, 'Person_InfoST', ?) Hibernate: insert into Person_InfoST (address, age, name, sex, empType, empid, exp, TYPE_PERSON, id) values (?, ?, ?, ?, ?, ?, ?, 'EMP', ?) Hibernate: insert into Person_InfoST (address, age, name, sex, degree, rollNum, TYPE_PERSON, id) values (?, ?, ?, ?, ?, ?, 'STD', ?)
  • 47. 47 Inheritance: Table Per class strategy 12/13/2021 Person_InfoTC @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Person_InfoTC { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int pid; private String name; private String age; private String sex; private String address;..} EmployeeTC @Entity public class EmployeeTC extends Person_InfoTC { private int empid; private String exp; private String empType; } StudentTc @Entity public class StudentTC extends Person_InfoTC { private String rollNum; private String degree; ..} TestInheritanceTPC Person_InfoTC person = new Person_InfoTC(); person.setName("Mallikarjuna"); person.setAge("100"); person.setAddress("Mysuru"); person.setSex("Male"); EmployeeTC emp = new EmployeeTC(); emp.setEmpType("Driver"); emp.setExp("12"); emp.setEmpid(1001); StudentTC student =new StudentTC(); student.setRollNum("1002"); student.setDegree("BSC"); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(person); session.save(emp); session.save(student); session.getTransaction().commit();
  • 48. 48 Inheritance: JOIN strategy 12/13/2021 In this no repeated column present in the table Person_InfoJS @Entity @Inheritance(strategy = InheritanceType.JOINED) public class Person_InfoJS { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int pid; private String name; private String age; private String sex; private String address; …} EmployeeJS @Entity public class EmployeeJS extends Person_InfoJS { private int empid; private String exp; private String empType;..} StudentJS @Entity public class StudentJS extends Person_InfoJS { private String rollNum; private String degree;..} TestInheritanceJS Person_InfoJS person = new Person_InfoJS(); person.setName("Mallikarjuna"); person.setAge("100"); person.setAddress("Mysuru"); person.setSex("Male"); EmployeeJS emp = new EmployeeJS(); emp.setEmpType("Driver"); emp.setExp("12"); emp.setEmpid(1001); StudentJS student =new StudentJS(); student.setRollNum("1002"); student.setDegree("BSC"); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(person); session.save(emp); session.save(student); session.getTransaction().commit();
  • 49. 49 CRUD 12/13/2021 @Entity public class UserCRUD { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; private String location; ..} SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); for(int count=0;count<=10; count++) { UserCRUD user =new UserCRUD(); user.setName("user"+count); user.setLocation("place"+count); session.save(user); } session.getTransaction().commit(); session.beginTransaction(); UserCRUD userCrud= session.get(UserCRUD.class, 5); System.out.println("USERCRUD::"+userCrud.getId() +" :: "+userCrud.getName()); session.getTransaction().commit();
  • 50. 50 CRUD 12/13/2021 session.beginTransaction(); userCrud= session.get(UserCRUD.class, 6); System.out.println("USERCRUD::"+userCrud.getId() +" :: "+userCrud.getName()); session.getTransaction().commit(); session.beginTransaction(); userCrud= session.get(UserCRUD.class, 7); session.delete(userCrud); System.out.println("USERCRUD::"+userCrud.getId() +" :: "+userCrud.getName()); session.getTransaction().commit(); session.beginTransaction(); userCrud= session.get(UserCRUD.class, 8); userCrud.setName("Pranet"); session.update(userCrud); System.out.println("USERCRUD::"+userCrud.getId() +" :: "+userCrud.getName()); session.getTransaction().commit();
  • 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()); }
  • 54. 54 HQL:Pagination 12/13/2021 SampleHQLPagination SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); TypedQuery<UserHQL> query = session.createQuery("from UserHQL"); query.setFirstResult(6); query.setMaxResults(5); 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.