Hibernate Notes
Hibernate Notes
Drawbacks of JDBC
Why frameworks?
The purpose of framework is to allow designers and developers to focus on building a unique feature for their web-
based projects rather than re-inventing by coding. Framework is specially created to help you boost the performance
and efficiency of your web app development task.
What is framework?
A framework is a structure that you can build software on. It serves as a foundation, so you're not starting entirely
from scratch. Frameworks are typically associated with a specific programming language and are suited to different
types of tasks.
Hibernate is a framework which provides some abstraction layer, meaning that the programmer does not have to
worry about the implementations, hibernate does the implementations for us internally like establishing a
connection with the database, writing query to perform CRUD operations etc.
It is a java framework which is used to develop persistence logic.
Persistence logic means to store and process the data for long use. More precisely Hibernate is an open-source, non-
invasive, light-weight java ORM (Object-relational mapping) framework to develop objects which are independent
of the database software and make independent persistence logic in all JAVA, JEE.
Hibernate is an ORM Tool.
Object-Relational Mapping (ORM) is a technique that lets you send query and manipulate data from a database using
an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the
Object-Relational Mapping technique, hence the phrase an ORM.
An ORM library is a completely ordinary library written in your language of choice that encapsulates the code
needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same
language you're using.
Any software that uses ORM technique is called as ORM Tool. Hibernate is an ORM Tool.
JPA stands for Java Persistence API (Application Programming Interface). It is a Java specification that gives some
functionality and standard to ORM tools.
It is used to examine, control, and persist data between Java objects and relational databases.
It is observed as a standard technique for Object Relational Mapping.
It is considered as a link between an object-oriented model and a relational database system. As it is a specification of
Java, JPA does not conduct any functioning by itself. Therefore, it needs implementation.
Hence, for data persistence ORM tools like Hibernate implements JPA specifications. For data persistence, the
javax.persistence package contains the JPA classes and interfaces.
Hibernate is a framework which is used to develop persistence logic which is independent of Database software.
In JDBC to develop persistence logic we deal with primitive types. Whereas Hibernate framework we use Objects to
develop persistence logic which are independent of database software. In hibernate every class will be mapped to
table and every object will be mapped to column or table data. To tell the program which class to be converted as
table we have to use annotation the line before class declaration, we have to declare an annotation as @Entity which
maps the class or creates the table for that class and object i.e., variable created will be considered as column.
By initializing the objects, we can insert data into table.
To declare any column as Primary key we will use @Id annotation before declaring that variable.
In a Class we can have only one primary key or @Id.
Transient state
Persistent state
➢ As soon as the object associated with the Session, it entered in the persistent state.
Hence, we can say that an object is in the persistence state when we save or persist it.
➢ Here, each object represents the row of the database table.
➢ So, modifications in the data make changes in the database.
Detached State
➢ Once we either close the session or clear its cache, then the object entered into the detached state.
➢ As an object is no more associated with the Session, modifications in the data don't affect any changes in the
database.
➢ However, the detached object still has a representation in the database.
➢ If we want to persist the changes made to a detached object, it is required to reattach the application to a
valid Hibernate session.
➢ 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.
Removed State
Explanation:
Here first Property name value is the path of the driver,
Second Property name value is the URL or address of the Database,
Third and fourth Property name value are the credentials required.
EntityManager is an interface used to allow applications to manage and search for entities in the relational database.
The EntityManager is an API that manages the lifecycle of entity instances.
An EntityManager object manages a set of entities that are defined by a persistence unit.
First, we will use setters to set the values to object and we will use persist () method and pass the object as parameter
which will save the object as table columns.
Remove () method will delete the values based on object. Before deleting an object, we have to make sure that the
object is present in the database. We also have find () method which will take class name and primary key as
arguments and will return the object if it is present else it will return null.
merge () is used to alter the table, it will also take object as the parameter.
For executing queries which don’t have particular methods we will use createQuery("HQL") method.
EntityTransaction is used whenever we are making changes to database or operations which will affect the database
then we will use EntityTransaction. There are two commonly used methods in EntityTransaction those are begin ()
and commit().
Before altering table values we should use begin() method and after writing the method which alters we have to use
commit() method to save the changes.
Note: -
To tell hibernate for which class table needs to be created we use @Entity above the declaration of the class.
To declare any variable as primary key we use @Id annotation. For every Entity class it is compulsory that it should
have one primary key.
To make a table name different from class name we use entity property name.
i.e., @Entity(name="new_name")
If we want to specify name for column other than variable name, we use column annotation
i.e., @Column(name="new_name")
To make a column Not Null we have to use nullable property of annotation column
i.e., @Column(nullable=true)
To restrict the length, we use length property but we don’t usually use this as it is already done in the frontend.
i.e., @Column(length=20)
Mapping
Hibernate mappings are one of the key features of hibernate, they help in establishing the relationship between two
database tables as attributes in our model that allows us to easily navigate the associations in our model and criteria
queries.
we can establish either uni-directional or bi-directional mapping i.e., we can either model them as an attribute on
only one of the associated entities or on both. It will not impact our database mapping tables, but it defines in which
direction you can use the relationship in your model and criteria queries.
The relationship that can be established between entities are: -
one to many/many to one — it represents the one-to-many relationship between two tables.
example: One Institution can have many branches. Similarly, many branches will have one head branch.
many to many — it represents the many to many relationships between two tables.
example: Many malls can have many items. Similarly, many items can be present in many malls.
Annotations Used:
@JoinColumn
If we don’t want one extra column to get created or in the case of one to many or many to many if we don’t want a
table to get created for the foreign key then we can use JoinColumn annotation in the parent class and mappedby
property in the child class and we can avoid the extra column or extra table.
Cascading
It is used in the case of mapping, implementing this, by making any changes to parent class it will affect the child
class. for example if we want to remove a table which has a child table linked to it, directly we cannot do that first
we have to delete the child table then only we can delete parent table but if we use cascading property, if we delete
parent table child table will get deleted directly.
@JoinTable
Used in the mapping of associations. It is specified on the owning side of an association.
A join table is typically used in the mapping of many-to-many and unidirectional one-to-many associations. It may
also be used to map bidirectional many-to-one/one-to-many associations, unidirectional many-to-one relationships,
and one-to-one associations (both bidirectional and unidirectional).
When a join table is used in mapping a relationship with an embeddable class on the owning side of the relationship,
the containing entity rather than the embeddable class is considered the owner of the relationship.
If the JoinTable annotation is missing, the default values of the annotation elements apply. The name of the join table
is assumed to be the table names of the associated primary tables concatenated together (owning side first) using an
underscore.
Caching
There are two levels of caching one is first-level and other is second level.
First-level catch is by default enabled.
First level cache is also known as EntityManager level cache as for every EntityManager there will be one cache.
Second level cache is not enabled by default, for enabling 2nd level cache we need to go to maven repository
download hibernate ehcache version same as hibernate version, copy paste the dependency in persistence.xml file.
This will enable Second Level cache which is of EntityManagerFactory level, for every EntityManagerFactory we
will have one 2nd level cache.
Drawback of 2nd level cache is even if we enable 2nd level cache first level cache will also be present which might
affect performance and speed.
Cache is basically used to avoid hitting database every single time. Once we perform specific task on database for the
first time automatically it will be stored in cache, so next time when we perform same task or request for the same
object it won’t hit the database directly it will provide from cache memory.
Generated Value
Fetch Types
When working with an ORM, data fetching/loading can be classified into two types:
eager and lazy.
Lazy Loading
Lazy Loading is a design pattern that we use to defer initialization of an object as long as it's possible.
Hibernate applies lazy loading approach on entities and associations by providing a proxy implementation of classes.
Advantages:
Eager Loading
Eager Loading is a design pattern in which data initialization occurs on the spot.
Advantages:
Example:
One User can have multiple OrderDetails. In eager loading strategy, if we load the User data, it will also load up all
orders associated with it and will store it in a memory.
But when we enable lazy loading, if we pull up a User, OrderDetail data won't be initialized and loaded into a
memory until we make an explicit call to it.
Programs: 1. Entity Class for Company
2.Entity Class for Employee