ADVANTAGES OF HIBERNATE
•Open Source and Lightweight
• Fast Performance
• Database Independent Query
• Automatic Table Creation
• Simplifies Complex Join
• Provides Query Statistics and Database Status
3.
ORM TOOL
• AnORM tool simplifies the data creation, data manipulation and data access. It is a programming
technique that maps the object as one row in the table in the database.
JAVA
APPLICATION
OBJECT ORM DATABASE
4.
DIFFERENT ORM TOOLS
Hibernate.
TopLink.
EclipseLink.
OpenJPA.
MyBatis (formally known as iBatis).
5.
HIBERNATE
• Hibernate isa Java framework that simplifies the development of Java
application to interact with the database. It is an open source, lightweight,
ORM (Object Relational Mapping) tool. Hibernate implements the
specifications of JPA (Java Persistence API) for data persistence.
6.
JPA
• Java PersistenceAPI (JPA) is a Java specification that provides certain functionality and standard to
ORM tools. The javax.persistence package contains the JPA classes and interfaces.
7.
ENTITY MANAGER FACTORY
•EntityManagerFactory provides instances of EntityManager for connecting to same database. All the
instances are configured to use the same setting as defined by the default implementation. Several entity
manager factories can be prepared for connecting to different data base.
• The EntityManagerFactory interface present in java.persistence package is used to provide an entity
manager.
• Persistence - The Persistence is a bootstrap class which is used to obtain an EntityManagerFactory interface.
Syntax :
EntityManagerFactory emf = Persistence.createEntityManagerFactory(“String”);//string = persistence unit
name.
8.
ENTITY MANAGER
• JPAEntityManager is used to access a database in a particular application. It is used to manage
persistent entity instances, to find entities by their primary key identity, and to query over all
entities.
• IMPORTANT METHODS :
• persist – Make an instance managed and persistent.
• merge – Merge the state of the given entity into the current persistence context.
• remove – Remove the entity instance.
• find – Find by primary key. Search for an entity of the specified class and primary key. If the entity instance is
contained in the persistence context, it is returned from there.
9.
Syntax :
EntityManagerFactory emf= Persistence.createEntityManagerFactory(“String”);//string =
persistence unit name
EntityManager em1 = EntityManagerFactory.createEntityManager();
EntityManager em2 = EntityManagerFactory.createEntityManager();
EntityManager em3 = EntityManagerFactory.createEntityManager();
NOTE : we can create multiple entity managers for one entity manager factory.
10.
ENTITYTRANSACTION
• Interface usedto control transactions on resource-local entity managers.
• IMPORTANT METHODS :
• begin() method - This method is used to start the transaction.
• commit() method - This method is used to commit the transaction.
Syntax :
EntityManagerFactory emf = Persistence.createEntityManagerFactory(“String”);//string = persistence unit
name
EntityManager em1 = EntityManagerFactory.createEntityManager();
EntityTransaction et = EntityManager.getTransaction();
11.
DIFFERENCE BETWEEN PERSISTAND MERGE
• Persist should be called only on
new entities.
• It will persist the entity object in
database.
• If you pass the object with duplicate
primary key it will throw exception.
• merge is meant to reattach
detached entities.
• It will update the object in the database
for duplicate key.
• If the primary key is not matched it will
insert the object as new record in table.
12.
MAPPING IN HIBERNATE
•The mapping of associations between entity classes and the relationships between tables is the
soul of ORM.
• hibernate mappings are one of the key features of hibernate. they establish the relationship
between two database tables as attributes in your model. that allows you to easily navigate the
associations in your model and criteria queries.
• you can establish either unidirectional or bidirectional i.e you can either model them as an
attribute on only one of the associated entities or on both. it will not impact your database
mapping tables, but it defines in which direction you can use the relationship in your model and
criteria queries.
ONE-TO-ONE MAPPING(UNI-DIRECTION)
• Oneto one represents that a single entity is associated with a single instance of the other entity. An instance
of a source entity can be at most mapped to one instance of the target entity.
• In this type of mapping one entity has a property or a column that references to a property or a column in the
target entity.
• Here you can retrive the data in one direction only i.e if you have person id you can get pan details also but
you cannot get person details with pan id.
Ex : One person has one pan, a pan is associated with a single person.
@Entity
public class Pan {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String address;
private String panNumber;
@Entity
public class Person {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private String email;
private long phone;
@OneToOne
private Pan pan;
15.
ONE-TO-ONE MAPPING(BI-DIRECTION)
• Bidirectionalassociation allows us to fetch details of dependent object from both side. In such case, we have
the reference of two classes in each other. Let's take an example of same Person and Pan, now Person class
has-a reference of Pan and Pan has a reference of Person.
• Here you can retrive the data in bi-direction .If you have person id you can get pan details and also you can
get person details with pan id.
Ex : One person has one pan, a pan is associated with a single person.
@Entity
public class Pan {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String address;
private String panNumber;
@OneToOne
private Person person;
@Entity
public class Person {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private String email;
private long phone;
@OneToOne
private Pan pan;
16.
ONE-TO-MANY MAPPING(UNI-DIRECTION)
• Inone-to-many mapping one entity is associated with many instances of other entity. for example one person
has many bank accounts.
• Here you can retrive the data in uni-direction .If you have person id you can get all the account details and you
cannot get person details with account id.
Ex : One person has many accounts, many accounts are associated with a single person.
@Entity
public class account{
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private long accNo;
private String ifscCode;
private Person person;
@Entity
public class Person {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private String email;
private long phone;
@OneToMany
private List<Account> accounts;
17.
MANY-TO-ONE MAPPING(UNI-DIRECTION)
• Inmany-to-one mapping many instances of entity is associated with one instance of other entity. for example
many branches have one hospital.
• Here you can retrive the data in uni-direction .If you have branch id you can get the hospital details and you
cannot get branch details with hospital id.
Ex : Many branches are associated with one hospital.
@Entity
public class Branch {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private String state;
private String country;
private long phone;
@ManyToOne
private Hospital hospital;
@Entity
public class Hospital {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private String web;
18.
MANY-TO-ONE OR ONE-TO-MANY(BI-DIRECTION)
•In bi-direction, in many-to-one mapping many instances of entity is associated with one instance of other
entity. for example many branches have one hospital . In one-to-many mapping one instance of entity is
associated with many instance of other entity. for example one hospital have many branches.
• Here you can retrive the data in bi-direction .If you have branch id you can get the hospital details and you can
get branch details with hospital id.
Ex : Many branches are associated with one hospital.
@Entity
public class Branch {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private String state;
private String country;
private long phone;
@ManyToOne
private Hospital hospital;
@Entity
public class Hospital {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private String web;
@OneToMany
private List<Branch> branches;
19.
MANY-TO-MANY MAPPING (UNI-DIRECTION)
•In many-to-many mapping many instances of entity is associated with many instances of other entity. for
example many students have many courses.
• Here you can retrive the data in uni-direction .If you have student id you can get the all the details of courses
but you cannot get student details with course id.
Ex : Many students are associated with many courses.
@Entity
public class Student {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private int age;
@ManyToMany
private List<Course> courses;
@Entity
public class Course {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private String duration;
20.
MANY-TO-MANY MAPPING (BI-DIRECTION)
•In many-to-many mapping many instances of entity is associated with many instances of other entity. for
example many students have many courses and many courses have many students.
• Here you can retrive the data in bi-direction .If you have student id you can get the all the details of courses
and you can get all student details with course id.
Ex : Many students are associated with many courses.
@Entity
public class Student {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private int age;
@ManyToMany
private List<Course> courses;
@Entity
public class Course {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private String duration;
@ManyToMany
private List<student> students;
21.
JPQL
• Java PersistenceQuery Language (JPQL) is a platform-independent object-oriented query language
defined as part of the Java Persistence API (JPA) specification. JPQL is used to make queries against
entities stored in a relational database. JPQL is inspired by SQL.
• JPQL is object-oriented. In JPQL we work with entities and collection of entities, while in SQL we
work with columns and rows.
22.
TYPES OF QUERYPARAMETERS
• Similar to JDBC prepared statement parameters, JPA specifies two different ways to write
parameterized queries by using:
Positional parameters
Named parameters
23.
MAPPEDBY AND @JOINCOLUMN
•JPA Relationships can be either unidirectional or bidirectional. It simply means we can model them as an attribute on
exactly one of the associated entities or both.
• Defining the direction of the relationship between entities has no impact on the database mapping. It only defines the
directions in which we use that relationship in our domain model.
• For a bidirectional relationship, we usually define:
the owning side
inverse or the referencing side
• The @JoinColumn annotation helps us specify the column we'll use for joining an entity association or element collection.
On the other hand, the mappedBy attribute is used to define the referencing side (non-owning side) of the relationship.
24.
BEFORE USING @JOINCOLUMNAND MAPPEDBY
@Entity
public class Charcy {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String cNo;
private String type;
@OneToOne
private Vehicle vehicle;
@Entity
public class Vehicle {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private double cost;
@OneToOne
private Charcy charcy;
TABLES IN DATABASE
issssid
charcy
id name cost charcy_id
issssid
id cNo type Vehicle_id
vehicle
25.
AFTER USING @JOINCOLUMNAND MAPPEDBY
@Entity
public class Charcy {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String cNo;
private String type;
@OneToOne(mappedBy=“charcy”)
private Vehicle vehicle;
@Entity
public class Vehicle {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
private double cost;
@OneToOne
@JoinColumn
private Charcy charcy;
TABLES IN DATABASE
issssid
charcy
id name cost charcy_id
issssid
id cNo type
vehicle
26.
@JOINTABLE ANNOTATION
• Whenwe use mapping in hibernate to build relationship between two entites ,
sometimes duplicate tables get created.
• To avoid this duplication in tables we use @JoinTable.
Ex :
@ManyToMany @JoinTable(joinColumns = @JoinColumn, inverseJoinColumns = @JoinColumn)
27.
BEFORE USING @JOINTABLE
@Entity
publicclass Cab {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String driverName;
private double cost;
@ManyToMany
private List<Person> persons;
@Entity
public class Person {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
@ManyToMany
private List<Cab> cabs;
TABLES IN DATABASE
issssid
cab
id name
issssid
id cost driverName
person
issssid
cab_id person_id
cab_person
issssid
person_cab
person_id cab_id
28.
AFTER USING @JOINTABLE
@Entity
publicclass Cab {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String driverName;
private double cost;
@ManyToMany(mappedBy = "cabs")
private List<Person> persons;
@Entity
public class Person {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private int id;
private String name;
@ManyToMany
@JoinTable(joinColumns =
@JoinColumn , inverseJoinColumns
= @JoinColumn)
private List<Cab> cabs;
TABLES IN DATABASE
issssid
cab
id name
issssid
id cost driverName
person
issssid
person_cab
persons_id cabs_id
29.
CASCADING IN HIBERNATE
•Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity
whenever the state of its relationship owner (superclass) affected. When the relationship owner
(superclass) is saved/ deleted, then the mapped entity associated with it should also be saved/
deleted automatically.
• When we perform some action on the target entity, the same action will be applied to the
associated entity.
30.
TYPES OF CASCADING
•All JPA-specific cascade operations are represented by the javax.persistence.CascadeType enum containing
entries:
ALL
PERSIST
MERGE
REMOVE
REFRESH
• DETACH
31.
FETCHTYPE
• When workingwith an ORM, data fetching/loading can be classified into two types: eager and lazy.
• In this quick tutorial, we are going to point out differences and show how we can use these in
Hibernate.
• Two types :
• 1.Lazy
• 2.Eager
32.
DIFFERENT FETCHTYPES
• LAZY:
• The FetchType.LAZY tells Hibernate to only
fetch the related entities from the
database when you use the relationship. This
is a good idea in general because there’s no
reason to select entities you don’t need for
your uses case.
• EAGER :
• The FetchType.EAGER tells Hibernate to get all
elements of a relationship when selecting the
root entity.
TRANSIENT STATE
o Thetransient state is the initial state of an object.
o Once we create an instance of POJO class, then the object entered in the transient state.
o Here, an object is not associated with the Session. So, the transient state is not related to any
database.
o Hence, modifications in the data don't affect any changes in the database.
o The transient objects exist in the heap memory. They are independent of Hibernate.
36.
PERSISTENT STATE
o Assoon as the object associated with the Session, it entered in the persistent state.
o Hence, we can say that an object is in the persistence state when we save or persist it.
o Here, each object represents the row of the database table.
o So, modifications in the data make changes in the database.
37.
DETACHED STATE
o Oncewe either close the session or clear its cache, then the object entered into the detached
state.
o As an object is no more associated with the Session, modifications in the data don't affect any
changes in the database.
o However, the detached object still has a representation in the database.
o If we want to persist the changes made to a detached object, it is required to reattach the
application to a valid Hibernate session.
o To associate the detached object with the new hibernate session, use any of these methods -
load(), merge(), refresh(), update() or save() on a new session with the reference of the detached
object.
38.
CACHING IN HIBERNATE
•Hibernate caching improves the performance of the application by pooling the object in the cache.
It is useful when we have to fetch the same data multiple times.
• There are mainly two types of caching:
o First Level Cache, and
o Second Level Cache
39.
FIRST-LEVEL CACHE
• Sessionobject holds the first level cache data. It is enabled by default. The first level cache data will
not be available to entire application. An application can use many session object.
40.
SECOND-LEVEL CACHE
• SessionFactoryobject holds the second level cache data. The data stored in the second level cache
will be available to entire application. But we need to enable it explicitely.
• Three steps to enable second level cache :
• 1.Add hibernate-echache dependency . (version should be same as hibernate version)
• 2.Add @cacheble annotation to Entity class.
• 3.Enable second-level cache by configuring in persistence.xml file.
COMPOSITE KEY INHIBERNATE
• A composite primary key, also called a composite key, is a combination of two or more columns to form a
primary key for a table.
• In JPA, we can define the composite keys by : the @Embaddable and @EmbeddedId annotations.
• In order to define the composite primary keys, we should follow some rules:
The composite primary key class must be public.
It must have a no-arg constructor.
It must define the equals() and hashCode() methods.
It must be Serializable.
43.
import
javax.persistence.EmbeddedId;
import
javax.persistence.Entity;
@Entity
public class User{
@EmbeddedId
private UserId userId;
private String name;
private int age;
private String gender;
private String password;
import java.io.Serializable;
import
javax.persistence.Embeddable;
@Embeddable
public class UserId implements
Serializable {
private String email;
private long phone;
44.
PERSISTENT UNIT INHIBERNATE
• A persistence unit defines a set of all entity classes that are managed by entity manager
instance in an application.
• It contains configurations file which is required for connection.
• It consists of url , username , password.
• It is used to perform actions on database.
PERSISTENCE.XML FILE
• Itis a standard configuration file.
• It has configurations for the Object-Relation mapping.
• It can have multiple persistence units to connect to different database.
• Persistence unit name must be unique.
• This persistence.xml file should be created in src/main/resources . create folder with
name META-INF and create persistence.xml file in it.