SlideShare a Scribd company logo
Hibernate
By - Mohit Kanwar
By - Mohit Kanwar
Pre-requisites
2
Technologies
• Java
• 6+
• SQL
• MySQL
• MSSQL
• H2
• Oracle
3
PreRequisites
©	Mohit	Kanwar
• Spring
• Maven
• Git
• XML
Required Good	To	Have
The Course Material
4
PreRequisites
©	Mohit	Kanwar
• These slides are hosted at :
https://www.slideshare.net/mohitkanwar1/hibernate-1-day/
The Code is available at :
https://github.com/mohitkanwar/hibernate-tutorial
• This course is divided into following categories
• The very basics
• Introduction to Hibernate
• Working with Hibernate
• Some Advanced Topics
• FAQs and further learning
The Very Basics
5 ©	Mohit	Kanwar
The Very Basics
• Object Oriented Programming and Programming Principles
• Application Design
• Database Connectivity
• JDBC Demo
• Introduction to ORM
Agenda
6 ©	Mohit	Kanwar
Object Oriented Programming
• Abstraction
• Dealing with Ideas rather than representations
• Inheritance
• Acquire and pass on
• Polymorphism
• Behaving according to context
• Encapsulation
• Related items bagged together
TheVeryBasics
7 ©	Mohit	Kanwar
Solid Principles
• Single Responsibility Principle
• Do only one thing, and do it perfectly
• Open-Close Principle
• open for extension, but closed for modification
• Liskov substitution Principle
• Replaceable by Children
• Interface segregation Principle
• Only declare mandatory
• Dependency Inversion Principle
• Abstractions should not depend on details. Details should depend on
abstractions.
TheVeryBasics
8 ©	Mohit	Kanwar
3 Tier Architecture
Front	End Business	Logic Database
TheVeryBasics
Introduction9 ©	Mohit	Kanwar
Responsibilities of each layer
Front	End Business	Logic Database
User	
Experience
Multi	
Channel
i18n
Fast
OOPs
Functional
Scalable
Performant
Libraries
Persistence
Transactional
TheVeryBasics
Focused areas
SQL
Index
Stored	
Procedures
Brandable
10 ©	Mohit	Kanwar
Technologies in each layer
Front	End Business	Logic Database
TheVeryBasics
Languages focused in specific areas11 ©	Mohit	Kanwar
Getting the Data : The Tasks
Front	
End
Business	
Logic
Database
Get	Connection
Prepare	Query
Execute	Query
Close	Connection
TheVeryBasics
12 ©	Mohit	Kanwar
Getting the Data : Solutions
Front	
End
Business	
Logic
Database
TheVeryBasics
13 ©	Mohit	Kanwar
Chose one of the technology to manage
the database.
JDBC
Hibernate
Spring	Data
iBatis
Java Database Connectivity (JDBC)
• JDBC is a Java API to connect to databases
• Different drivers are available to connect to different databases
• Driver jars may be OS Dependent
• It involves higher maintenance cost with scaling of the
application
TheVeryBasics
14 ©	Mohit	Kanwar
Application Architecture
TheVeryBasics
Controller Service DAO
POJO
15 ©	Mohit	Kanwar
JDBC Demo
TheVeryBasics
16 ©	Mohit	Kanwar
Project Setup
• Install a database (e.g. MySQL)
• Install an IDE (e.g. IntelliJ)
• Setup a Java Project
TheVeryBasics:JDBCDemo
17 ©	Mohit	Kanwar
Application Design : Users
• UserController
• create User
• getAllUsers
• UserService
• create User
• getAllUsers
• User
• firstname
• lastname
• dateOfJoining
18
TheVeryBasics:JDBCDemo
©	Mohit	Kanwar
• Schema
• Table
• USERS
• FNAME
• LNAME
• DOJ
Application Design : DB Setup
• Create Queries
• Create Connection
• Add Driver Jars
19
TheVeryBasics:JDBCDemo
©	Mohit	Kanwar
Service
• Create Statement
• Setup the statement with query and query parameters
• Execute the statement
• Traverse through the Result Set
• Create User Objects
TheVeryBasics:JDBCDemo
20 ©	Mohit	Kanwar
User POJO
• POJO Class for business Purposes
• Contains the Domain Model of the Object to be persisted
TheVeryBasics:JDBCDemo
21 ©	Mohit	Kanwar
Database Table
• Create the table
• Populate with seed data
• Optional : create indexes/triggers etc
TheVeryBasics:JDBCDemo
22 ©	Mohit	Kanwar
Post Demo Discussions
• What are the code improvements that we can do?
• Can we make CRUD operations aligned towards business
models, instead of database tables?
• How difficult is it to move from MySQL to Oracle?
• Different types in MySQL and Oracle
• Converting Java Types to respective DB Types
• Can we implement inheritance in database tables?
• How do we define uniqueness?
• Can we add some more features?
TheVeryBasics:JDBCDemo
23 ©	Mohit	Kanwar
Object Oriented Queries : A few points
• Move Hardcoding to properties
• Making java code more flexible
• Segregate Domain logic from Table Row
• Single place of type conversion
• Creating configuration of mapping table to Domain Model
• Utility to do db operations segregated from domain logic
• utility.save(user)
• utility.update(student)
• Adding features like Connection Management, Caching, Query
tuning would help
TheVeryBasics
24 ©	Mohit	Kanwar
Type System Mismatch
Java Oracle Microsoft SQL	Server
String Varchar	(length)	,	CLOB VARCHAR,NVARCHAR
Char, char Char CHAR
int,	Integer Integer, NUMERIC,BIGINT
Boolean,	boolean Boolean BOOLEAN
Long,	long,Float Float Binary_Double
Date Date DATETIME
Object RAW BINARY
TheVeryBasics
25 ©	Mohit	Kanwar
Removing dependency on underlying database
Object Relational Mapping
• Object-relational mapping is a technique for converting data
between incompatible type systems using object-
oriented programming languages.
• This creates, in effect, a "virtual object database" that can be
used from within the programming language. There are both
free and commercial packages available that perform object-
relational mapping, although some programmers opt to
construct their own ORM tools.
https://en.wikipedia.org/wiki/Object-relational_mapping
TheVeryBasics
26 ©	Mohit	Kanwar
Object Relational Mismatch
TheVeryBasics
ID NAME USERCONTACTID
1 Gavin	King Contact-1
USERCONTACTID CONTACTTYPE CONTACTTYPEID
Contact-1 EMAIL EMAIL-1
Contact-1 PHONE PHONE-1
CONTACTTYPEID EMAIL
EMAIL-1 gking@example.com
CONTACTTYPEID PHONE
PHONE-1 +91-9000000000
User
Contacts
Email
Phone
27 ©	Mohit	Kanwar
Inheritance Mismatch
TheVeryBasics
ID NAME USERCONTACTID EmployeeId
1 Gavin	King Contact-1 1
User
ID DEPARTMENT
1 Finance
Employee
28 ©	Mohit	Kanwar
Identity Mismatch
• Identity vs Equality
• == vs .equals
• The ID Column in table
TheVeryBasics
29 ©	Mohit	Kanwar
Why ORM Tools
• Domain Model Pattern
• Focus on business concepts and not on relational DB Structure
• Interconnected Objects
• Each object is a meaningful concept
• Object Oriented
• Inheritance
• Encapsulation
• Object Identity
• Navigate through the Object Graph instead of relational model
• Increased Development Speed
• Portability
• Mostly DB Independent
• Query Abstractions
• Performance
• Caching
• More Control
TheVeryBasics
30 ©	Mohit	Kanwar
Java Persistence API
• Aka JPA
• JSR 317 (2.0) & JSR 338 (2.1)
• Included in Java SE and Java EE
• Provides portability between JPA Implementations (with some
limitations)
• Standardized ORM Concepts, API and query language (JPQL)
TheVeryBasics
31 ©	Mohit	Kanwar
Hibernate Basics
32
Hibernate Basics
• Introduction to Hibernate
• Architecture of applications using hibernate
• Hibernate Configurations
• Setting up Project
Agenda
33 ©	Mohit	Kanwar
Introduction to Hibernate
• Hibernate is an Open Source, lightweight ORM Tool
• It simplifies the database interactions of a Java application.
• It helps in representing data as business units and hides the
database implementation details
• It has a huge community and it’s code can be found at
https://github.com/hibernate/hibernate-orm
• The official documentation of Hibernate can be found at
http://hibernate.org/orm/documentation/5.2/
HibernateBasics
34 ©	Mohit	Kanwar
Why Hibernate?
• It is a fast performing ORM tool
• It provides a Database Independent Query Language
• Tools available to synchronize business model and database
• it simplifies complex Joins
• Provides query statistics and database status
• 100% TCK Compliant
• It is highly configurable.
• It provides simple APIs to store and retrieve data
HibernateBasics
35 ©	Mohit	Kanwar
Hibernate Architecture
HibernateBasics
36
Database
ControllerView Service
Business Model
DAL
Configurations Configurations
Non Hibernate Hibernate Database
Session
Transactions
Caching
Query
Mapping Database
View Model
©	Mohit	Kanwar
Data Persistence
• Hibernate works with existing Java Object Model
• Model is marked as persistent by creating required configuration
• Mapping is created for business models and DB tables
HibernateBasics
37 ©	Mohit	Kanwar
Data Persistence States
HibernateBasics
38
Transient
Persistent
Detached
In Memory
In DB
©	Mohit	Kanwar
Hibernate Configurations
• Configuration
HibernateBasics
Database	Configuration Domain	Model	-Table	mapping Optional	Configurations
39
hibernate.connection.driver_class
hibernate.connection.url
hibernate.connection.username
hibernate.connection.password
hibernate.dialect
classname.hbm.xml
annotations	based
hibernate.show_sql
hibernate.format_sql
hibernate.jdbc.fetch_size
hibernate.jdbc.batch_size
hibernate.hbm2ddl.auto
hibernate.connection.pool_size
©	Mohit	Kanwar
The		native	driver	class	to	be	used	for	
managing	the	DB	Connection.	This	
would	be	the	standard	JDBC	driver	
classes.
URL	for	the	database	server
Username	to	connect	to	the	database
Password	(if	any)	for	the	userDialect	for	the	SQL	queries	to	be	
executed
Mappings	between	Entity	class	and	
Database	Tables
Database Configuration
• Configurtions can be achieved using any of the following types
of configuration
• XML based : hibernate.cfg.xml
• Properties based : hibernate.properties
• Passed through command line
• Programmatic Configuration
HibernateBasics
40 ©	Mohit	Kanwar
XML Based Mapping
HibernateBasics
<?xml	version	= "1.0" encoding	= "utf-8"?>
<!DOCTYPE	hibernate-mapping	PUBLIC	"-//Hibernate/Hibernate	Mapping	DTD//EN"	
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name = "User" table = "USERS "	>
<meta attribute = "class-description"> This	class	contains	the	details	of	Users.	</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/> </id>
<property name = "name" column = "FULL_NAME" type = "string"/>
<property name = "email" column = ”EMAIL" type = " string	"/>
</class>
</hibernate-mapping>
41 ©	Mohit	Kanwar
Annotation Based Mapping
HibernateBasics
import	javax.persistence.*;
@Entity
@Table(name	=	"USERS")
public	class	User	{
@Id
@Column(name	=	"ID")
@GeneratedValue(strategy	=	GenerationType.AUTO)
private	int id;
@Column(name	=	"FULL_NAME")
private	String	name;
@Column(name	=	"EMAIL")
private	String	email;
//Getters	and	Setters
}
42 ©	Mohit	Kanwar
Working with Hibernate
43
©	Mohit	Kanwar
Agenda
• Setting up your workspace
• Create Operation
• Update Operation
• Delete Operation
• Retrieve Operation
• HQL
• Criteria
• Hibernate Tools
WorkingwithHibernate
44 ©	Mohit	Kanwar
Setting up your workspace
WorkingwithHibernate
45 ©	Mohit	Kanwar
• Create Project Structure
• Create folder structure
• Create Java Project
• Add Hibernate and MySQL Dependencies
• Create hibernate configuration
• Create the mapping file
Creating the project Structure
WorkingwithHibernate
46 ©	Mohit	Kanwar
• We are going to use a maven project for the same.
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
Database	
Connector
hibernate
Maven	
Compiler	
Plugin
Create Hibernate Configurations
WorkingwithHibernate
47 ©	Mohit	Kanwar
• We are going to use hibernate.cfg.xml for defining hibernate
configurations
• <classname>.hbm.xml files for defining mappings
Create Hibernate Configurations
WorkingwithHibernate
48 ©	Mohit	Kanwar
<?xml	version="1.0"	encoding="UTF-8"?>
<!DOCTYPE	hibernate-configuration	PUBLIC
"-//Hibernate/Hibernate	Configuration	DTD	3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property	name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property	name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property	name="hibernate.connection.url">jdbc:mysql://localhost:3306/demo</property>
<property	name="hibernate.connection.username">root</property>
<property	name="hibernate.connection.password">root</property>
<property	name="hibernate.connection.pool_size">1</property>
<property	name="hibernate.current_session_context_class">thread</property>
<property	name="hibernate.show_sql">true</property>
<property	name="packagesToScan">com.mk.tutorials.hibernate</property>
<mapping		class="com.mk.tutorials.hibernate.User"	resource="User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Create Hibernate Mappings
WorkingwithHibernate
49 ©	Mohit	Kanwar
<class	name="com.mk.tutorials.hibernate.User"	table="USERS">
<id	name="username"	column="USERNAME"	type="java.lang.String"	>
<generator	class="assigned"></generator>
</id>
<property	name="firstname"	column="FIRSTNAME"	type="java.lang.String"/>
<property	name="lastname"	column="LASTNAME"	type="java.lang.String"/>
<property	name="doj"	column="DOJ"	type="java.util.Date"/>
</class>
Creating a row in DB
WorkingwithHibernate
50 ©	Mohit	Kanwar
• An object instance is equivalent to a row in database
• Hibernate allows us to be agnostic about the database
• While working with hibernate, we are concerned about the session
• Hibernate manages creation of rows automatically
Session
• The main runtime interface between a Java application and
Hibernate.
• The lifecycle of a Session is bounded by the beginning and end
of a logical transaction.
• Session offers CRUD operations for mapped entity classes
• Sessions are created by SessionFactory
• SessionFactory is generally one per application
WorkingwithHibernate
51 ©	Mohit	Kanwar
Transactions
• A Transaction is a set of instructions, which are treated as a
single unit of work.
• They should either be completed, or no partial of it should have
been executed.
WorkingwithHibernate
52 ©	Mohit	Kanwar
Transactions : ACID
WorkingwithHibernate
53 ©	Mohit	Kanwar
Atomicity
• Single	unit	
of	operation
• It	should	
either	be	
complete	or	
not	at	all
• No	middle	
state
Consistency
• Consistency	
of	referential	
integrity
Isolation
• Each	
transaction	
must	be	
isolated	
from	others
Durability
• Changes	are	
stored	
permanently
• Must	not	be	
erased	due	
to	system	
failure
Saving a User
WorkingwithHibernate
54 ©	Mohit	Kanwar
public	void	createUser(User	user)	{
Session	session	=	sessionFactory.openSession();
Transaction	t	=	session.beginTransaction();
session.save(user);
t.commit();
session.close();
}
Persist a User
WorkingwithHibernate
55 ©	Mohit	Kanwar
public	void	createUser(User	user)	{
Session	session	=	sessionFactory.openSession();
Transaction	t	=	session.beginTransaction();
session.persist(user);
t.commit();
session.close();
}
Save vs Persist
WorkingwithHibernate
56 ©	Mohit	Kanwar
• Returns the generated ID
after saving
• Session.save() for a
detached object will create a
new row.
• It is void. ID is not returned
• Session.persist() for a
detached object will
throw PersistentObjectExcep
tion as it is not allowed.
Updating the row
WorkingwithHibernate
57 ©	Mohit	Kanwar
• What is ID?
• What is equals method?
• Remember the concept of Identity Mismatch?
ID
• Id is used to identify an entity.
• It is analogues to Primary Key in DB Table.
• Id value can be assigned or generated.
• In Hibernate Entities, it is mandatory to define an Id.
WorkingwithHibernate
58 ©	Mohit	Kanwar
Equals
• Default implementation is available in object class and
corresponds to == operator a.k.a referential check
• .equals(Object o) should be over-ridden if a behaviour equality
is desired.
• Hibernate uses the Id to find the row in table, hence equals
method should correspond the same behaviour.
WorkingwithHibernate
59 ©	Mohit	Kanwar
https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html
Update the row
WorkingwithHibernate
60 ©	Mohit	Kanwar
@Override
public	void	update(User	user)	{
Session	session	=	sessionFactory.openSession();
Transaction	t	=	session.beginTransaction();
session.update(user);
t.commit();
session.close();
}
@Override
public	void	update(User	user)	{
Session	session	=	sessionFactory.openSession();
Transaction	t	=	session.beginTransaction();
session.update(user);
t.commit();
session.close();
}
Delete the row
WorkingwithHibernate
61 ©	Mohit	Kanwar
@Override
public	void	delete(User	user)	{
Session	session	=	sessionFactory.openSession();
Transaction	t	=	session.beginTransaction();
session.delete(user);
t.commit();
session.close();
}
Fetch all rows by Query *
WorkingwithHibernate
62 ©	Mohit	Kanwar
public	List<User>	getAllUsers()	{
Session	session	=	sessionFactory.openSession();
List<User>	users	=	session.createQuery("from	User").list();
session.close();
return	users;
}
select	user0_.USERNAME	as	USERNAME1_0_,	user0_.FIRSTNAME	as	FIRSTNAM2_0_,	user0_.LASTNAME	
as	LASTNAME3_0_,	user0_.DOJ	as	DOJ4_0_	from	USERS	user0_
Fetch rows using Criteria *
WorkingwithHibernate
63 ©	Mohit	Kanwar
public	List<User>	getAllUsers()	{
Session	session	=	sessionFactory.openSession();
Criteria	cr =	session.createCriteria(User.class);
List<User>	users	=	cr.list();
session.close();
return	users;
}
Mapping using annotations
WorkingwithHibernate
64 ©	Mohit	Kanwar
import	javax.persistence.Column;
import	javax.persistence.Entity;
import	javax.persistence.Id;
import	java.util.Date;
import	java.util.Objects;
@Entity
@Table	(name	=	"USERS")
public	class	User	implements	java.io.Serializable {
@Id
@Column(name	=	"USERNAME")
private	String	username;
@Column(name	=	"FIRSTNAME")
private	String	firstname;
@Column(name	=	"LASTNAME")
private	String	lastname;
@Column(name	=	"DOJ")
private	Date	doj;
<mapping	class="com.mk.tutorials.hibernate.User"/>
Hibernate Query Language
65
©	Mohit	Kanwar
Introduction
• Hibernate Query Language (HQL) is a database independent
Structural Query Language
• It is closer to a Java developer as compared to SQL
• It makes use of Class names instead of Table names
• It is object oriented way of accessing an SQL db
66
WorkingwithHibernate:HQL
©	Mohit	Kanwar
Query Interface
• OOPs way of representing a db query
• It abstracts out the db implementation underneath
67
WorkingwithHibernate:HQL
©	Mohit	Kanwar
Aliases
• Aliases are useful in giving names to Entities
• "FROM User AS U”
• The keyword “As” is optional
• “FROM User U”
68
WorkingwithHibernate:HQL
©	Mohit	Kanwar
“SELECT u.firstname FROM User u”
Where Clause
69
WorkingwithHibernate:HQL
©	Mohit	Kanwar
"SELECT firstname FROM User WHERE username = 'myusername'"
Prepared Statement
70
WorkingwithHibernate:HQL
©	Mohit	Kanwar
public	List<String>	getSomeFirstNames(String	name)	{
Session	session	=	sessionFactory.openSession();
String	stringQuery =	"SELECT	firstname FROM	User	WHERE	username	=	:uname";
Query	hql =	session.createQuery(stringQuery);
hql.setString("uname",name);
List<String>	users	=	hql.list();
session.close();
return	users;
}
Aggregate Functions
71
WorkingwithHibernate:HQL
©	Mohit	Kanwar
Sum
Avg
Min
Max
Count
Other Queries
72
WorkingwithHibernate:HQL
©	Mohit	Kanwar
“UPDATE User SET name=:n WHERE id=:i”
“DELETE User WHERE id=:i”
“DELETE User WHERE id >=:i”
Using SQL with Hibernate
73
WorkingwithHibernate
©	Mohit	Kanwar
public	List<User>	getAllUsersBySQL()	{
Session	session	=	sessionFactory.openSession();
String	sqlQuery =	"SELECT	*	FROM	USERS";
Query	query	=	session.createSQLQuery(sqlQuery)
.addEntity(User.class);
List<User>	users	=	query.list();
session.close();
return	users;
}
Native Query
Entity Mapping
Criteria API
• Criteria is object oriented representation of the criteria for the
query
• You can add multiple restrictions in the criteria and define the
query behavior.
74
WorkingwithHibernate
©	Mohit	Kanwar
Batch Processing
• Hibernate caches all the newly inserted entity instances in
session level cache.
• Creating more instances (in the same transaction) than the
available memory may lead to OutOfMemoryException
• Make use of hibernate.jdbc.batch_size property
• Flush the session during insertion
• Clear the cache during insertion
75
WorkingwithHibernate
©	Mohit	Kanwar
Batch Processing
76
WorkingwithHibernate
©	Mohit	Kanwar
public	void	createUsers(List<User>	users){
Session	session	=	sessionFactory.openSession();
Transaction	t	=	session.beginTransaction();
int batchSize =	Integer.parseInt(configuration.getProperties().getProperty("hibernate.jdbc.batch_size"));
for(int i =	0	;i <	users.size();	i++){
session.save(users.get(i));
if(i %	batchSize==0){
session.flush();
session.clear();
}
}
t.commit();
session.close();
}
Hibernate Tools
WorkingwithHibernate
77 ©	Mohit	Kanwar
• Mapping Editors
• Hibernate Console
• Reverse Engineering
• Wizards
• Ant Tasks
http://hibernate.org/tools/
Advanced Concepts
78
©	Mohit	Kanwar
Agenda
• ID Generation Strategies
• Inheritance Strategies
AdvancedConcepts
79 ©	Mohit	Kanwar
EntityManager
• An EntityManager is a JPA Standard
• It’s instance is associated with a persistence context.
• The EntityManager API is used to create and remove persistent
entity instances, to find entities by their primary key, and to
query over entities.
• EntityManager is created by EntityManagerFactory
WorkingwithHibernate
80
JPA
©	Mohit	Kanwar
ID Generation Strategies
• GenerationType.AUTO
• Hibernate choses GenerationType.SEQUENCE as default for most dbs
• GenerationType.IDENTITY
• auto-incremented database column, DB decides
• GenerationType.SEQUENCE
• Uses a DB Sequence to generate ID
• Define your own Strategy
WorkingwithHibernate
81
JPA
https://www.thoughts-on-java.org/jpa-generate-primary-keys/
©	Mohit	Kanwar
ID Example
WorkingwithHibernate
82
@Id
@Column(name	=	"ID")
@GeneratedValue(strategy	=	GenerationType.AUTO)
private	int id;
ID NAME EMAIL …
1 … … …
2 … … …
3 … … …
©	Mohit	Kanwar
Composite Key for IDs
WorkingwithHibernate
83
StudentID CourseID TestDate Score
1 1 … …
2 1 … …
2 2 … …
Test_Score_History
@Embeddable
public	class	TestScoreHistoryKey implements	Serializable{
private	long	studentId;
private	long	courseId;
@Entity
@Table(name	=	"TEST_SCORE_HISTORY")
public	class	TestScoreHistory {
@Id
private	TestScoreHistoryKey key;
private	Date	testDate;
private	float	score;
©	Mohit	Kanwar
Composite Key for IDs
WorkingwithHibernate
84
StudentID CourseID TestDate Score
1 1 … …
2 1 … …
2 2 … …
Test_Score_History
public	class	TestScoreHistoryKey implements	Serializable{
private	long	studentId;
private	long	courseId;
@Entity
@Table(name	=	"TEST_SCORE_HISTORY")
public	class	TestScoreHistory {
@EmbeddedId
private	TestScoreHistoryKey key;
private	Date	testDate;
private	float	score;
©	Mohit	Kanwar
Composite Key for IDs : Points to Note
• The Composite Key Class
• must implement Serializable
Interface
• must define equals and hashcode
methods
• must have a default constructor
85
WorkingwithHibernate
public	class	TestScoreHistoryKey implements	Serializable{
private	long	studentId;
private	long	courseId;
public	long	getStudentId()	{…}
public	void	setStudentId(long	studentId)	{…}
public	long	getCourseId()	{…}
public	void	setCourseId(long	courseId)	{…}
@Override
public	boolean equals(Object	o)	{…}
@Override
public	int hashCode()	{… }
©	Mohit	Kanwar
Inheritance in Hibernate
WorkingwithHibernate
86
• Multiple entities can be represented in database following
Inheritance pattern
• Developer needs to decide a strategy for inheritance
• Available strategies are
• Single Table
• Table per Class
• Joined
©	Mohit	Kanwar
Inheritance : Single Table
WorkingwithHibernate
87
User
• userId
• password
• fullname
@Entity
@Inheritance(strategy	=	InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name	=	"DTYPE",discriminatorType =	
DiscriminatorType.STRING)
@DiscriminatorValue(value	=	"STUDENT")
public	class	Student	extends	User{
@Column(name	=	"ENROLLMENTDATE")
private	Date	enrollmentDate;
• All Elements are in same table
• Entities are differentiated on basis of a column in table
• Inherited class will have a specified discriminator value
userId password fullname DTYPE enrollmentDate
Student
• enrollmentDate
©	Mohit	Kanwar
Inheritance : Table per Class
WorkingwithHibernate
88
User
• userId
• password
• fullname
Student
• enrollmentDate
Employee
• employeeId
userId password fullname enrollmentDate
Student
userId password fullname employeeID
Employee
©	Mohit	Kanwar
Inheritance : Joined
WorkingwithHibernate
89
User
• userId
• password
• fullname
Student
• enrollmentDate
Employee
• employeeId
userId password fullname
User
userId enrollmentDate
Student
userId employeeID
Employee
©	Mohit	Kanwar
Working with Collection
• OneToMany
• ManyToOne
• ManyToMany
WorkingwithHibernate
90 ©	Mohit	Kanwar
Hibernate Search
WorkingwithHibernate
91 ©	Mohit	Kanwar
Foreign Keys
WorkingwithHibernate
92 ©	Mohit	Kanwar
Joins
WorkingwithHibernate
93 ©	Mohit	Kanwar
Lazy Loading
WorkingwithHibernate
94 ©	Mohit	Kanwar
Caching
WorkingwithHibernate
95 ©	Mohit	Kanwar
Shortcomings of Hibernate
• Hibernate cannot work on tables without Primary Key.
• However, having a PK is a good practice in general
• Performance Tuning still needs to be done natively
HibernateFundamentals
96 ©	Mohit	Kanwar
Frequently Asked
Questions
©	Mohit	Kanwar97
What are the key components of
Hibernate?
• Configuration
• DB Configurations
• Mappings
• SessioFactory
• Session
• Transaction
• Query
• Criteria
98
FAQ
©	Mohit	Kanwar
What are the best practices that hibernate
recommends for persistent classes?
• default constructor
• ID
• private attribute with getters and setters
• persistent classes should either be non-final or implement an
interface that declares all public methods as hibernate uses
proxies internally
99
FAQ
©	Mohit	Kanwar
What are the alternatives to Hibernate?
• Java Data Objects
• iBatis
• Spring Data Access Objects
• Any framework which follows JPA
100
FAQ
©	Mohit	Kanwar
Can we use Hibernate with NOSQL
Databases?
• Hibernate is built to be used with Relational Databases
• Although it is technically possible to design your application
using hibernate which works with both SQL as well as NOSQL
databases, it will lead to some design and performance costs
• Hibernate OGM is a module created for NOSQL databases.
101
FAQ
©	Mohit	Kanwar
https://stackoverflow.com/questions/2153195/hibernate-with-mongodb
References
• https://www.javatpoint.com/hibernate-tutorial
• https://en.wikipedia.org/wiki/Object-relational_mapping
• Just Hibernate - By Madhusudhan Konda
• https://www.tutorialspoint.com/hibernate/index.htm
• http://hibernate.org/orm/documentation/5.2/
• https://www.slideshare.net/VladMihalcea/high-performance-hibernate-devoxx-france
• https://www.slideshare.net/alimenkou/why-do-i-hate-hibernate-12998784
• https://www.thoughts-on-java.org/jpa-generate-primary-keys/
• https://docs.jboss.org/ejb3/app-server/tutorial/singleinheritance/single.html
• http://docs.jboss.org/hibernate/core/3.5/reference/en/html/mapping.html#mapping-
declaration-id
• https://www.linkedin.com/pulse/what-hibernate-java-allen-peter/
• https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html
102 ©	Mohit	Kanwar
Recommended Further Reading
• https://martinfowler.com/bliki/OrmHate.html
• https://vladmihalcea.com/how-to-implement-a-custom-string-
based-sequence-identifier-generator-with-hibernate/
• https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/i
nheritance.html
• https://www.javatpoint.com/hibernate-and-spring-integration
• http://hibernate.org/ogm/
• https://vladmihalcea.com/a-beginners-guide-to-jpa-and-
hibernate-cascade-types/
103 ©	Mohit	Kanwar
About Me
104 ©	Mohit	Kanwar
• Mohit Kanwar
• Email :
• m.m.kanwar@gmail.com
• Social
• https://www.linkedin.com/in/mohit-kanwar-7668a211/
• https://github.com/mohitkanwar
• https://www.slideshare.net/mohitkanwar1
• Blog
• http://mohitkanwar.com
A performance review
ProgrammingBasics
“More than half of application performance
bottlenecks originate in the database, but most
application teams have little or no visibility into
database performance.”
https://www.appdynamics.com/database/
- Appdynamics
105 ©	Mohit	Kanwar
Thankyou!
©	Mohit	Kanwar106

More Related Content

What's hot

Spring Boot
Spring BootSpring Boot
Spring Boot
Pei-Tang Huang
 
Hibernate
HibernateHibernate
Hibernate
Ajay K
 
jQuery
jQueryjQuery
jQuery
Jay Poojara
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring DataAnton Sulzhenko
 
Hibernate
HibernateHibernate
Hibernate
Prashant Kalkar
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Edureka!
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
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
kamal kotecha
 
Spring Core
Spring CoreSpring Core
Spring Core
Pushan Bhattacharya
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
José Paumard
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
Thibaud Desodt
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
Anurag
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
José Paumard
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 

What's hot (20)

Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Hibernate
HibernateHibernate
Hibernate
 
jQuery
jQueryjQuery
jQuery
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring Data
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate I
Hibernate IHibernate I
Hibernate I
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
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
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 

Similar to Introduction to Hibernate Framework

Cloud-native Data
Cloud-native DataCloud-native Data
Cloud-native Data
cornelia davis
 
Cloud-Native-Data with Cornelia Davis
Cloud-Native-Data with Cornelia DavisCloud-Native-Data with Cornelia Davis
Cloud-Native-Data with Cornelia Davis
VMware Tanzu
 
Prominent Back-end frameworks to consider in 2022!
Prominent Back-end frameworks to consider in 2022!Prominent Back-end frameworks to consider in 2022!
Prominent Back-end frameworks to consider in 2022!
Shelly Megan
 
Velociraptor - SANS Summit 2019
Velociraptor - SANS Summit 2019Velociraptor - SANS Summit 2019
Velociraptor - SANS Summit 2019
Velocidex Enterprises
 
Cloud-native Data: Every Microservice Needs a Cache
Cloud-native Data: Every Microservice Needs a CacheCloud-native Data: Every Microservice Needs a Cache
Cloud-native Data: Every Microservice Needs a Cache
cornelia davis
 
Frameworks Galore: A Pragmatic Review
Frameworks Galore: A Pragmatic ReviewFrameworks Galore: A Pragmatic Review
Frameworks Galore: A Pragmatic Review
netc2012
 
Angular Or React – Don’t Roll The Dice
Angular Or React – Don’t Roll The DiceAngular Or React – Don’t Roll The Dice
Angular Or React – Don’t Roll The Dice
Synerzip
 
Building Big Architectures
Building Big ArchitecturesBuilding Big Architectures
Building Big Architectures
Ramit Surana
 
NoSQL Simplified: Schema vs. Schema-less
NoSQL Simplified: Schema vs. Schema-lessNoSQL Simplified: Schema vs. Schema-less
NoSQL Simplified: Schema vs. Schema-less
InfiniteGraph
 
Basics of Backbone.js
Basics of Backbone.jsBasics of Backbone.js
Basics of Backbone.js
Avishekh Bharati
 
Modular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireModular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter Bonfire
Jeff Fox
 
GeeCon Prague 2023 - Unleash the power of your applications with Micronaut®, ...
GeeCon Prague 2023 - Unleash the power of your applications with Micronaut®, ...GeeCon Prague 2023 - Unleash the power of your applications with Micronaut®, ...
GeeCon Prague 2023 - Unleash the power of your applications with Micronaut®, ...
Juarez Junior
 
Sitecore - what to look forward to
Sitecore - what to look forward toSitecore - what to look forward to
Sitecore - what to look forward to
jinto77
 
Portal and Intranets
Portal and Intranets Portal and Intranets
Portal and Intranets
Redar Ismail
 
Transforming to Microservices
Transforming to MicroservicesTransforming to Microservices
Transforming to Microservices
Kyle Brown
 
SevillaJUG - Unleash the power of your applications with Micronaut® ,GraalVM...
SevillaJUG - Unleash the power of your applications with Micronaut®  ,GraalVM...SevillaJUG - Unleash the power of your applications with Micronaut®  ,GraalVM...
SevillaJUG - Unleash the power of your applications with Micronaut® ,GraalVM...
Juarez Junior
 
Sitecore9 key features by jitendra soni - Presented in Sitecore User Group UK
Sitecore9 key features by jitendra soni - Presented in Sitecore User Group UKSitecore9 key features by jitendra soni - Presented in Sitecore User Group UK
Sitecore9 key features by jitendra soni - Presented in Sitecore User Group UK
Jitendra Soni
 
NoSQL on the move
NoSQL on the moveNoSQL on the move
NoSQL on the move
Codemotion
 

Similar to Introduction to Hibernate Framework (20)

Cloud-native Data
Cloud-native DataCloud-native Data
Cloud-native Data
 
Cloud-Native-Data with Cornelia Davis
Cloud-Native-Data with Cornelia DavisCloud-Native-Data with Cornelia Davis
Cloud-Native-Data with Cornelia Davis
 
Seminar.pptx
Seminar.pptxSeminar.pptx
Seminar.pptx
 
Prominent Back-end frameworks to consider in 2022!
Prominent Back-end frameworks to consider in 2022!Prominent Back-end frameworks to consider in 2022!
Prominent Back-end frameworks to consider in 2022!
 
Velociraptor - SANS Summit 2019
Velociraptor - SANS Summit 2019Velociraptor - SANS Summit 2019
Velociraptor - SANS Summit 2019
 
Cloud-native Data: Every Microservice Needs a Cache
Cloud-native Data: Every Microservice Needs a CacheCloud-native Data: Every Microservice Needs a Cache
Cloud-native Data: Every Microservice Needs a Cache
 
Frameworks Galore: A Pragmatic Review
Frameworks Galore: A Pragmatic ReviewFrameworks Galore: A Pragmatic Review
Frameworks Galore: A Pragmatic Review
 
Angular Or React – Don’t Roll The Dice
Angular Or React – Don’t Roll The DiceAngular Or React – Don’t Roll The Dice
Angular Or React – Don’t Roll The Dice
 
Building Big Architectures
Building Big ArchitecturesBuilding Big Architectures
Building Big Architectures
 
NoSQL Simplified: Schema vs. Schema-less
NoSQL Simplified: Schema vs. Schema-lessNoSQL Simplified: Schema vs. Schema-less
NoSQL Simplified: Schema vs. Schema-less
 
Microservices
MicroservicesMicroservices
Microservices
 
Basics of Backbone.js
Basics of Backbone.jsBasics of Backbone.js
Basics of Backbone.js
 
Modular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireModular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter Bonfire
 
GeeCon Prague 2023 - Unleash the power of your applications with Micronaut®, ...
GeeCon Prague 2023 - Unleash the power of your applications with Micronaut®, ...GeeCon Prague 2023 - Unleash the power of your applications with Micronaut®, ...
GeeCon Prague 2023 - Unleash the power of your applications with Micronaut®, ...
 
Sitecore - what to look forward to
Sitecore - what to look forward toSitecore - what to look forward to
Sitecore - what to look forward to
 
Portal and Intranets
Portal and Intranets Portal and Intranets
Portal and Intranets
 
Transforming to Microservices
Transforming to MicroservicesTransforming to Microservices
Transforming to Microservices
 
SevillaJUG - Unleash the power of your applications with Micronaut® ,GraalVM...
SevillaJUG - Unleash the power of your applications with Micronaut®  ,GraalVM...SevillaJUG - Unleash the power of your applications with Micronaut®  ,GraalVM...
SevillaJUG - Unleash the power of your applications with Micronaut® ,GraalVM...
 
Sitecore9 key features by jitendra soni - Presented in Sitecore User Group UK
Sitecore9 key features by jitendra soni - Presented in Sitecore User Group UKSitecore9 key features by jitendra soni - Presented in Sitecore User Group UK
Sitecore9 key features by jitendra soni - Presented in Sitecore User Group UK
 
NoSQL on the move
NoSQL on the moveNoSQL on the move
NoSQL on the move
 

Recently uploaded

Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 

Recently uploaded (20)

Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 

Introduction to Hibernate Framework

  • 1. Hibernate By - Mohit Kanwar By - Mohit Kanwar
  • 3. Technologies • Java • 6+ • SQL • MySQL • MSSQL • H2 • Oracle 3 PreRequisites © Mohit Kanwar • Spring • Maven • Git • XML Required Good To Have
  • 4. The Course Material 4 PreRequisites © Mohit Kanwar • These slides are hosted at : https://www.slideshare.net/mohitkanwar1/hibernate-1-day/ The Code is available at : https://github.com/mohitkanwar/hibernate-tutorial • This course is divided into following categories • The very basics • Introduction to Hibernate • Working with Hibernate • Some Advanced Topics • FAQs and further learning
  • 5. The Very Basics 5 © Mohit Kanwar
  • 6. The Very Basics • Object Oriented Programming and Programming Principles • Application Design • Database Connectivity • JDBC Demo • Introduction to ORM Agenda 6 © Mohit Kanwar
  • 7. Object Oriented Programming • Abstraction • Dealing with Ideas rather than representations • Inheritance • Acquire and pass on • Polymorphism • Behaving according to context • Encapsulation • Related items bagged together TheVeryBasics 7 © Mohit Kanwar
  • 8. Solid Principles • Single Responsibility Principle • Do only one thing, and do it perfectly • Open-Close Principle • open for extension, but closed for modification • Liskov substitution Principle • Replaceable by Children • Interface segregation Principle • Only declare mandatory • Dependency Inversion Principle • Abstractions should not depend on details. Details should depend on abstractions. TheVeryBasics 8 © Mohit Kanwar
  • 9. 3 Tier Architecture Front End Business Logic Database TheVeryBasics Introduction9 © Mohit Kanwar
  • 10. Responsibilities of each layer Front End Business Logic Database User Experience Multi Channel i18n Fast OOPs Functional Scalable Performant Libraries Persistence Transactional TheVeryBasics Focused areas SQL Index Stored Procedures Brandable 10 © Mohit Kanwar
  • 11. Technologies in each layer Front End Business Logic Database TheVeryBasics Languages focused in specific areas11 © Mohit Kanwar
  • 12. Getting the Data : The Tasks Front End Business Logic Database Get Connection Prepare Query Execute Query Close Connection TheVeryBasics 12 © Mohit Kanwar
  • 13. Getting the Data : Solutions Front End Business Logic Database TheVeryBasics 13 © Mohit Kanwar Chose one of the technology to manage the database. JDBC Hibernate Spring Data iBatis
  • 14. Java Database Connectivity (JDBC) • JDBC is a Java API to connect to databases • Different drivers are available to connect to different databases • Driver jars may be OS Dependent • It involves higher maintenance cost with scaling of the application TheVeryBasics 14 © Mohit Kanwar
  • 17. Project Setup • Install a database (e.g. MySQL) • Install an IDE (e.g. IntelliJ) • Setup a Java Project TheVeryBasics:JDBCDemo 17 © Mohit Kanwar
  • 18. Application Design : Users • UserController • create User • getAllUsers • UserService • create User • getAllUsers • User • firstname • lastname • dateOfJoining 18 TheVeryBasics:JDBCDemo © Mohit Kanwar • Schema • Table • USERS • FNAME • LNAME • DOJ
  • 19. Application Design : DB Setup • Create Queries • Create Connection • Add Driver Jars 19 TheVeryBasics:JDBCDemo © Mohit Kanwar
  • 20. Service • Create Statement • Setup the statement with query and query parameters • Execute the statement • Traverse through the Result Set • Create User Objects TheVeryBasics:JDBCDemo 20 © Mohit Kanwar
  • 21. User POJO • POJO Class for business Purposes • Contains the Domain Model of the Object to be persisted TheVeryBasics:JDBCDemo 21 © Mohit Kanwar
  • 22. Database Table • Create the table • Populate with seed data • Optional : create indexes/triggers etc TheVeryBasics:JDBCDemo 22 © Mohit Kanwar
  • 23. Post Demo Discussions • What are the code improvements that we can do? • Can we make CRUD operations aligned towards business models, instead of database tables? • How difficult is it to move from MySQL to Oracle? • Different types in MySQL and Oracle • Converting Java Types to respective DB Types • Can we implement inheritance in database tables? • How do we define uniqueness? • Can we add some more features? TheVeryBasics:JDBCDemo 23 © Mohit Kanwar
  • 24. Object Oriented Queries : A few points • Move Hardcoding to properties • Making java code more flexible • Segregate Domain logic from Table Row • Single place of type conversion • Creating configuration of mapping table to Domain Model • Utility to do db operations segregated from domain logic • utility.save(user) • utility.update(student) • Adding features like Connection Management, Caching, Query tuning would help TheVeryBasics 24 © Mohit Kanwar
  • 25. Type System Mismatch Java Oracle Microsoft SQL Server String Varchar (length) , CLOB VARCHAR,NVARCHAR Char, char Char CHAR int, Integer Integer, NUMERIC,BIGINT Boolean, boolean Boolean BOOLEAN Long, long,Float Float Binary_Double Date Date DATETIME Object RAW BINARY TheVeryBasics 25 © Mohit Kanwar Removing dependency on underlying database
  • 26. Object Relational Mapping • Object-relational mapping is a technique for converting data between incompatible type systems using object- oriented programming languages. • This creates, in effect, a "virtual object database" that can be used from within the programming language. There are both free and commercial packages available that perform object- relational mapping, although some programmers opt to construct their own ORM tools. https://en.wikipedia.org/wiki/Object-relational_mapping TheVeryBasics 26 © Mohit Kanwar
  • 27. Object Relational Mismatch TheVeryBasics ID NAME USERCONTACTID 1 Gavin King Contact-1 USERCONTACTID CONTACTTYPE CONTACTTYPEID Contact-1 EMAIL EMAIL-1 Contact-1 PHONE PHONE-1 CONTACTTYPEID EMAIL EMAIL-1 gking@example.com CONTACTTYPEID PHONE PHONE-1 +91-9000000000 User Contacts Email Phone 27 © Mohit Kanwar
  • 28. Inheritance Mismatch TheVeryBasics ID NAME USERCONTACTID EmployeeId 1 Gavin King Contact-1 1 User ID DEPARTMENT 1 Finance Employee 28 © Mohit Kanwar
  • 29. Identity Mismatch • Identity vs Equality • == vs .equals • The ID Column in table TheVeryBasics 29 © Mohit Kanwar
  • 30. Why ORM Tools • Domain Model Pattern • Focus on business concepts and not on relational DB Structure • Interconnected Objects • Each object is a meaningful concept • Object Oriented • Inheritance • Encapsulation • Object Identity • Navigate through the Object Graph instead of relational model • Increased Development Speed • Portability • Mostly DB Independent • Query Abstractions • Performance • Caching • More Control TheVeryBasics 30 © Mohit Kanwar
  • 31. Java Persistence API • Aka JPA • JSR 317 (2.0) & JSR 338 (2.1) • Included in Java SE and Java EE • Provides portability between JPA Implementations (with some limitations) • Standardized ORM Concepts, API and query language (JPQL) TheVeryBasics 31 © Mohit Kanwar
  • 33. Hibernate Basics • Introduction to Hibernate • Architecture of applications using hibernate • Hibernate Configurations • Setting up Project Agenda 33 © Mohit Kanwar
  • 34. Introduction to Hibernate • Hibernate is an Open Source, lightweight ORM Tool • It simplifies the database interactions of a Java application. • It helps in representing data as business units and hides the database implementation details • It has a huge community and it’s code can be found at https://github.com/hibernate/hibernate-orm • The official documentation of Hibernate can be found at http://hibernate.org/orm/documentation/5.2/ HibernateBasics 34 © Mohit Kanwar
  • 35. Why Hibernate? • It is a fast performing ORM tool • It provides a Database Independent Query Language • Tools available to synchronize business model and database • it simplifies complex Joins • Provides query statistics and database status • 100% TCK Compliant • It is highly configurable. • It provides simple APIs to store and retrieve data HibernateBasics 35 © Mohit Kanwar
  • 36. Hibernate Architecture HibernateBasics 36 Database ControllerView Service Business Model DAL Configurations Configurations Non Hibernate Hibernate Database Session Transactions Caching Query Mapping Database View Model © Mohit Kanwar
  • 37. Data Persistence • Hibernate works with existing Java Object Model • Model is marked as persistent by creating required configuration • Mapping is created for business models and DB tables HibernateBasics 37 © Mohit Kanwar
  • 39. Hibernate Configurations • Configuration HibernateBasics Database Configuration Domain Model -Table mapping Optional Configurations 39 hibernate.connection.driver_class hibernate.connection.url hibernate.connection.username hibernate.connection.password hibernate.dialect classname.hbm.xml annotations based hibernate.show_sql hibernate.format_sql hibernate.jdbc.fetch_size hibernate.jdbc.batch_size hibernate.hbm2ddl.auto hibernate.connection.pool_size © Mohit Kanwar The native driver class to be used for managing the DB Connection. This would be the standard JDBC driver classes. URL for the database server Username to connect to the database Password (if any) for the userDialect for the SQL queries to be executed Mappings between Entity class and Database Tables
  • 40. Database Configuration • Configurtions can be achieved using any of the following types of configuration • XML based : hibernate.cfg.xml • Properties based : hibernate.properties • Passed through command line • Programmatic Configuration HibernateBasics 40 © Mohit Kanwar
  • 41. XML Based Mapping HibernateBasics <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name = "User" table = "USERS " > <meta attribute = "class-description"> This class contains the details of Users. </meta> <id name = "id" type = "int" column = "id"> <generator class="native"/> </id> <property name = "name" column = "FULL_NAME" type = "string"/> <property name = "email" column = ”EMAIL" type = " string "/> </class> </hibernate-mapping> 41 © Mohit Kanwar
  • 42. Annotation Based Mapping HibernateBasics import javax.persistence.*; @Entity @Table(name = "USERS") public class User { @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "FULL_NAME") private String name; @Column(name = "EMAIL") private String email; //Getters and Setters } 42 © Mohit Kanwar
  • 44. Agenda • Setting up your workspace • Create Operation • Update Operation • Delete Operation • Retrieve Operation • HQL • Criteria • Hibernate Tools WorkingwithHibernate 44 © Mohit Kanwar
  • 45. Setting up your workspace WorkingwithHibernate 45 © Mohit Kanwar • Create Project Structure • Create folder structure • Create Java Project • Add Hibernate and MySQL Dependencies • Create hibernate configuration • Create the mapping file
  • 46. Creating the project Structure WorkingwithHibernate 46 © Mohit Kanwar • We are going to use a maven project for the same. <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.11.Final</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> Database Connector hibernate Maven Compiler Plugin
  • 47. Create Hibernate Configurations WorkingwithHibernate 47 © Mohit Kanwar • We are going to use hibernate.cfg.xml for defining hibernate configurations • <classname>.hbm.xml files for defining mappings
  • 48. Create Hibernate Configurations WorkingwithHibernate 48 © Mohit Kanwar <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/demo</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.pool_size">1</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.show_sql">true</property> <property name="packagesToScan">com.mk.tutorials.hibernate</property> <mapping class="com.mk.tutorials.hibernate.User" resource="User.hbm.xml"/> </session-factory> </hibernate-configuration>
  • 49. Create Hibernate Mappings WorkingwithHibernate 49 © Mohit Kanwar <class name="com.mk.tutorials.hibernate.User" table="USERS"> <id name="username" column="USERNAME" type="java.lang.String" > <generator class="assigned"></generator> </id> <property name="firstname" column="FIRSTNAME" type="java.lang.String"/> <property name="lastname" column="LASTNAME" type="java.lang.String"/> <property name="doj" column="DOJ" type="java.util.Date"/> </class>
  • 50. Creating a row in DB WorkingwithHibernate 50 © Mohit Kanwar • An object instance is equivalent to a row in database • Hibernate allows us to be agnostic about the database • While working with hibernate, we are concerned about the session • Hibernate manages creation of rows automatically
  • 51. Session • The main runtime interface between a Java application and Hibernate. • The lifecycle of a Session is bounded by the beginning and end of a logical transaction. • Session offers CRUD operations for mapped entity classes • Sessions are created by SessionFactory • SessionFactory is generally one per application WorkingwithHibernate 51 © Mohit Kanwar
  • 52. Transactions • A Transaction is a set of instructions, which are treated as a single unit of work. • They should either be completed, or no partial of it should have been executed. WorkingwithHibernate 52 © Mohit Kanwar
  • 53. Transactions : ACID WorkingwithHibernate 53 © Mohit Kanwar Atomicity • Single unit of operation • It should either be complete or not at all • No middle state Consistency • Consistency of referential integrity Isolation • Each transaction must be isolated from others Durability • Changes are stored permanently • Must not be erased due to system failure
  • 54. Saving a User WorkingwithHibernate 54 © Mohit Kanwar public void createUser(User user) { Session session = sessionFactory.openSession(); Transaction t = session.beginTransaction(); session.save(user); t.commit(); session.close(); }
  • 55. Persist a User WorkingwithHibernate 55 © Mohit Kanwar public void createUser(User user) { Session session = sessionFactory.openSession(); Transaction t = session.beginTransaction(); session.persist(user); t.commit(); session.close(); }
  • 56. Save vs Persist WorkingwithHibernate 56 © Mohit Kanwar • Returns the generated ID after saving • Session.save() for a detached object will create a new row. • It is void. ID is not returned • Session.persist() for a detached object will throw PersistentObjectExcep tion as it is not allowed.
  • 57. Updating the row WorkingwithHibernate 57 © Mohit Kanwar • What is ID? • What is equals method? • Remember the concept of Identity Mismatch?
  • 58. ID • Id is used to identify an entity. • It is analogues to Primary Key in DB Table. • Id value can be assigned or generated. • In Hibernate Entities, it is mandatory to define an Id. WorkingwithHibernate 58 © Mohit Kanwar
  • 59. Equals • Default implementation is available in object class and corresponds to == operator a.k.a referential check • .equals(Object o) should be over-ridden if a behaviour equality is desired. • Hibernate uses the Id to find the row in table, hence equals method should correspond the same behaviour. WorkingwithHibernate 59 © Mohit Kanwar https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html
  • 60. Update the row WorkingwithHibernate 60 © Mohit Kanwar @Override public void update(User user) { Session session = sessionFactory.openSession(); Transaction t = session.beginTransaction(); session.update(user); t.commit(); session.close(); } @Override public void update(User user) { Session session = sessionFactory.openSession(); Transaction t = session.beginTransaction(); session.update(user); t.commit(); session.close(); }
  • 61. Delete the row WorkingwithHibernate 61 © Mohit Kanwar @Override public void delete(User user) { Session session = sessionFactory.openSession(); Transaction t = session.beginTransaction(); session.delete(user); t.commit(); session.close(); }
  • 62. Fetch all rows by Query * WorkingwithHibernate 62 © Mohit Kanwar public List<User> getAllUsers() { Session session = sessionFactory.openSession(); List<User> users = session.createQuery("from User").list(); session.close(); return users; } select user0_.USERNAME as USERNAME1_0_, user0_.FIRSTNAME as FIRSTNAM2_0_, user0_.LASTNAME as LASTNAME3_0_, user0_.DOJ as DOJ4_0_ from USERS user0_
  • 63. Fetch rows using Criteria * WorkingwithHibernate 63 © Mohit Kanwar public List<User> getAllUsers() { Session session = sessionFactory.openSession(); Criteria cr = session.createCriteria(User.class); List<User> users = cr.list(); session.close(); return users; }
  • 64. Mapping using annotations WorkingwithHibernate 64 © Mohit Kanwar import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import java.util.Date; import java.util.Objects; @Entity @Table (name = "USERS") public class User implements java.io.Serializable { @Id @Column(name = "USERNAME") private String username; @Column(name = "FIRSTNAME") private String firstname; @Column(name = "LASTNAME") private String lastname; @Column(name = "DOJ") private Date doj; <mapping class="com.mk.tutorials.hibernate.User"/>
  • 66. Introduction • Hibernate Query Language (HQL) is a database independent Structural Query Language • It is closer to a Java developer as compared to SQL • It makes use of Class names instead of Table names • It is object oriented way of accessing an SQL db 66 WorkingwithHibernate:HQL © Mohit Kanwar
  • 67. Query Interface • OOPs way of representing a db query • It abstracts out the db implementation underneath 67 WorkingwithHibernate:HQL © Mohit Kanwar
  • 68. Aliases • Aliases are useful in giving names to Entities • "FROM User AS U” • The keyword “As” is optional • “FROM User U” 68 WorkingwithHibernate:HQL © Mohit Kanwar “SELECT u.firstname FROM User u”
  • 70. Prepared Statement 70 WorkingwithHibernate:HQL © Mohit Kanwar public List<String> getSomeFirstNames(String name) { Session session = sessionFactory.openSession(); String stringQuery = "SELECT firstname FROM User WHERE username = :uname"; Query hql = session.createQuery(stringQuery); hql.setString("uname",name); List<String> users = hql.list(); session.close(); return users; }
  • 72. Other Queries 72 WorkingwithHibernate:HQL © Mohit Kanwar “UPDATE User SET name=:n WHERE id=:i” “DELETE User WHERE id=:i” “DELETE User WHERE id >=:i”
  • 73. Using SQL with Hibernate 73 WorkingwithHibernate © Mohit Kanwar public List<User> getAllUsersBySQL() { Session session = sessionFactory.openSession(); String sqlQuery = "SELECT * FROM USERS"; Query query = session.createSQLQuery(sqlQuery) .addEntity(User.class); List<User> users = query.list(); session.close(); return users; } Native Query Entity Mapping
  • 74. Criteria API • Criteria is object oriented representation of the criteria for the query • You can add multiple restrictions in the criteria and define the query behavior. 74 WorkingwithHibernate © Mohit Kanwar
  • 75. Batch Processing • Hibernate caches all the newly inserted entity instances in session level cache. • Creating more instances (in the same transaction) than the available memory may lead to OutOfMemoryException • Make use of hibernate.jdbc.batch_size property • Flush the session during insertion • Clear the cache during insertion 75 WorkingwithHibernate © Mohit Kanwar
  • 76. Batch Processing 76 WorkingwithHibernate © Mohit Kanwar public void createUsers(List<User> users){ Session session = sessionFactory.openSession(); Transaction t = session.beginTransaction(); int batchSize = Integer.parseInt(configuration.getProperties().getProperty("hibernate.jdbc.batch_size")); for(int i = 0 ;i < users.size(); i++){ session.save(users.get(i)); if(i % batchSize==0){ session.flush(); session.clear(); } } t.commit(); session.close(); }
  • 77. Hibernate Tools WorkingwithHibernate 77 © Mohit Kanwar • Mapping Editors • Hibernate Console • Reverse Engineering • Wizards • Ant Tasks http://hibernate.org/tools/
  • 79. Agenda • ID Generation Strategies • Inheritance Strategies AdvancedConcepts 79 © Mohit Kanwar
  • 80. EntityManager • An EntityManager is a JPA Standard • It’s instance is associated with a persistence context. • The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. • EntityManager is created by EntityManagerFactory WorkingwithHibernate 80 JPA © Mohit Kanwar
  • 81. ID Generation Strategies • GenerationType.AUTO • Hibernate choses GenerationType.SEQUENCE as default for most dbs • GenerationType.IDENTITY • auto-incremented database column, DB decides • GenerationType.SEQUENCE • Uses a DB Sequence to generate ID • Define your own Strategy WorkingwithHibernate 81 JPA https://www.thoughts-on-java.org/jpa-generate-primary-keys/ © Mohit Kanwar
  • 83. Composite Key for IDs WorkingwithHibernate 83 StudentID CourseID TestDate Score 1 1 … … 2 1 … … 2 2 … … Test_Score_History @Embeddable public class TestScoreHistoryKey implements Serializable{ private long studentId; private long courseId; @Entity @Table(name = "TEST_SCORE_HISTORY") public class TestScoreHistory { @Id private TestScoreHistoryKey key; private Date testDate; private float score; © Mohit Kanwar
  • 84. Composite Key for IDs WorkingwithHibernate 84 StudentID CourseID TestDate Score 1 1 … … 2 1 … … 2 2 … … Test_Score_History public class TestScoreHistoryKey implements Serializable{ private long studentId; private long courseId; @Entity @Table(name = "TEST_SCORE_HISTORY") public class TestScoreHistory { @EmbeddedId private TestScoreHistoryKey key; private Date testDate; private float score; © Mohit Kanwar
  • 85. Composite Key for IDs : Points to Note • The Composite Key Class • must implement Serializable Interface • must define equals and hashcode methods • must have a default constructor 85 WorkingwithHibernate public class TestScoreHistoryKey implements Serializable{ private long studentId; private long courseId; public long getStudentId() {…} public void setStudentId(long studentId) {…} public long getCourseId() {…} public void setCourseId(long courseId) {…} @Override public boolean equals(Object o) {…} @Override public int hashCode() {… } © Mohit Kanwar
  • 86. Inheritance in Hibernate WorkingwithHibernate 86 • Multiple entities can be represented in database following Inheritance pattern • Developer needs to decide a strategy for inheritance • Available strategies are • Single Table • Table per Class • Joined © Mohit Kanwar
  • 87. Inheritance : Single Table WorkingwithHibernate 87 User • userId • password • fullname @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "DTYPE",discriminatorType = DiscriminatorType.STRING) @DiscriminatorValue(value = "STUDENT") public class Student extends User{ @Column(name = "ENROLLMENTDATE") private Date enrollmentDate; • All Elements are in same table • Entities are differentiated on basis of a column in table • Inherited class will have a specified discriminator value userId password fullname DTYPE enrollmentDate Student • enrollmentDate © Mohit Kanwar
  • 88. Inheritance : Table per Class WorkingwithHibernate 88 User • userId • password • fullname Student • enrollmentDate Employee • employeeId userId password fullname enrollmentDate Student userId password fullname employeeID Employee © Mohit Kanwar
  • 89. Inheritance : Joined WorkingwithHibernate 89 User • userId • password • fullname Student • enrollmentDate Employee • employeeId userId password fullname User userId enrollmentDate Student userId employeeID Employee © Mohit Kanwar
  • 90. Working with Collection • OneToMany • ManyToOne • ManyToMany WorkingwithHibernate 90 © Mohit Kanwar
  • 96. Shortcomings of Hibernate • Hibernate cannot work on tables without Primary Key. • However, having a PK is a good practice in general • Performance Tuning still needs to be done natively HibernateFundamentals 96 © Mohit Kanwar
  • 98. What are the key components of Hibernate? • Configuration • DB Configurations • Mappings • SessioFactory • Session • Transaction • Query • Criteria 98 FAQ © Mohit Kanwar
  • 99. What are the best practices that hibernate recommends for persistent classes? • default constructor • ID • private attribute with getters and setters • persistent classes should either be non-final or implement an interface that declares all public methods as hibernate uses proxies internally 99 FAQ © Mohit Kanwar
  • 100. What are the alternatives to Hibernate? • Java Data Objects • iBatis • Spring Data Access Objects • Any framework which follows JPA 100 FAQ © Mohit Kanwar
  • 101. Can we use Hibernate with NOSQL Databases? • Hibernate is built to be used with Relational Databases • Although it is technically possible to design your application using hibernate which works with both SQL as well as NOSQL databases, it will lead to some design and performance costs • Hibernate OGM is a module created for NOSQL databases. 101 FAQ © Mohit Kanwar https://stackoverflow.com/questions/2153195/hibernate-with-mongodb
  • 102. References • https://www.javatpoint.com/hibernate-tutorial • https://en.wikipedia.org/wiki/Object-relational_mapping • Just Hibernate - By Madhusudhan Konda • https://www.tutorialspoint.com/hibernate/index.htm • http://hibernate.org/orm/documentation/5.2/ • https://www.slideshare.net/VladMihalcea/high-performance-hibernate-devoxx-france • https://www.slideshare.net/alimenkou/why-do-i-hate-hibernate-12998784 • https://www.thoughts-on-java.org/jpa-generate-primary-keys/ • https://docs.jboss.org/ejb3/app-server/tutorial/singleinheritance/single.html • http://docs.jboss.org/hibernate/core/3.5/reference/en/html/mapping.html#mapping- declaration-id • https://www.linkedin.com/pulse/what-hibernate-java-allen-peter/ • https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html 102 © Mohit Kanwar
  • 103. Recommended Further Reading • https://martinfowler.com/bliki/OrmHate.html • https://vladmihalcea.com/how-to-implement-a-custom-string- based-sequence-identifier-generator-with-hibernate/ • https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/i nheritance.html • https://www.javatpoint.com/hibernate-and-spring-integration • http://hibernate.org/ogm/ • https://vladmihalcea.com/a-beginners-guide-to-jpa-and- hibernate-cascade-types/ 103 © Mohit Kanwar
  • 104. About Me 104 © Mohit Kanwar • Mohit Kanwar • Email : • m.m.kanwar@gmail.com • Social • https://www.linkedin.com/in/mohit-kanwar-7668a211/ • https://github.com/mohitkanwar • https://www.slideshare.net/mohitkanwar1 • Blog • http://mohitkanwar.com
  • 105. A performance review ProgrammingBasics “More than half of application performance bottlenecks originate in the database, but most application teams have little or no visibility into database performance.” https://www.appdynamics.com/database/ - Appdynamics 105 © Mohit Kanwar