Caching:
First-level cache:
- Hibernate first level cache is associated with the Session object.
- Enabled by default and, no way to disable it.
- There are methods through which the selected objects can be deleted from the cache or clear the cache completely.
- Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.
- We can use session
evict()
method to remove a single object from the hibernate first level cache. - We can use session
clear()
method to clear the cache i.e delete all the objects from the cache. - We can use session
contains()
method to check if an object is present in the hibernate cache or not, if the object is found in cache, it returns true or else it returns false. - Since hibernate cache all the objects into session first level cache, while running bulk queries or batch updates it’s necessary to clear the cache at certain intervals to avoid memory issues.
- Why do we need it ?:
- Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session).
- If cached copy of entity is present in first level cache, it is returned as result of load method.
- If there is no cached entity in first level cache, then second level cache is looked up for cached entity.
- If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again.
- If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.
- Second level cache validate itself for modified entities, if modification has been done through hibernate session APIs.
- If some user or process make changes directly in database, the there is no way that second level cache update itself until “timeToLiveSeconds” duration has passed for that cache region. In this case, it is good idea to invalidate whole cache and let hibernate build its cache once again. You can use below code snippet to invalidate whole hibernate second level cache.
get():
Both are used to retrieve objects by identifier.
The following Hibernate code snippet retrieves a User object from the database:
User user = (User) session.get(User.class, userID);
- It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
- If no row found , it will throws an ObjectNotFoundException.
when retrieving an object, avoiding a database hit if the object is already cached.
Hibernate also provides a load() method:
User user = (User) session.load(User.class, userID);
load():
The load() method is older; get() was added to Hibernate’s API due to userrequest. The difference is trivial:
If load() can’t find the object in the cache or database, an exception is
thrown. The load() method never returns null. The get() method returns
null if the object can’t be found.
The load() method may return a proxy instead of a real persistent instance.
A proxy is a placeholder that triggers the loading of the real object when it’s
accessed for the first time; we discuss proxies later in this section. On the
other hand, get() never returns a proxy.
Choosing between get() and load() is easy: If you’re certain the persistent
object exists, and nonexistence would be considered exceptional, load() is a
good option. If you aren’t certain there is a persistent instance with the given
identifier, use get() and test the return value to see if it’s null. Using load() has
a further implication: The application may retrieve a valid reference (a proxy) to a
persistent instance without hitting the database to retrieve its persistent state. So
load() might not throw an exception when it doesn’t find the persistent object
in the cache or database; the exception would be thrown later, when the proxy
is accessed.
Of course, retrieving an object by identifier isn’t as flexible as using arbitrary
queries.
3) Query Cache:
Query Cache is responsible for caching the combination of query and values provided as parameters as key, and list of identifiers of objects returned by query execution as values. Note that using Query Cache requires a second level cache too because when query result is get from cache (that is a list of identifiers), Hibernate will load objects using cached identifiers from second level.
To sum up, and as a conceptual schema, given next query: "from Country where population > :number", after first execution, Hibernate caches would contain next fictional values (note that number parameter is set to 1000):
The following four caching strategies are available:
1) Read-only:
- Useful for data that is read frequently but never updated.
- simplest and best-performing cache strategy.
2) Read/write:
- Read/write caches may be appropriate if your data needs to be updated.
- Carry more overhead than read-only caches.
3) Nonstrict read/write:
- Does not guarantee that two transactions will not simultaneously modify the same data.
- Therefore, it may be most appropriate for data that is read often but only occasionally modified.
4) Transactional:
- This is a fully transactional cache that may be used only in a JTA environment.
The Criteria interface is used to represent a query in a persistent class.
The Session is used to create the Criteria instances.
Criteria crit = sess.createCriteria(Cat.class);
It helps in Narrowing the result set
The class org.hibernate.criterion.Restrictions defines factory methods for obtaining certain built-in Criterion types.
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name", "Fritz%") )
.add( Restrictions.between("weight", minWeight, maxWeight) )
.list();
Restrictions can be grouped logically.
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name", "Fritz%") )
.add( Restrictions.or(
Restrictions.eq( "age", new Integer(0) ),
Restrictions.isNull("age")
) )
.list();
Ordering the results
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name", "F%")
.addOrder( Order.asc("name") )
.addOrder( Order.desc("age") )
.setMaxResults(50)
.list();
One to one
Oneto many
Many to one
Many to many
Lazy Loading:
- Lazy setting decides whether to load child objects while loading the Parent Object.
- Set respective hibernate mapping file of the parent class.Lazy = true (not to load child)
- By default the lazy loading of the child objects is true.
- This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.
- In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.
- In some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.
FAQ
-
Hibernate interview questions
Difference between session.save() , session.saveOrUpdate() and session.persist()? view answer
Q.What is the difference between hibernate and jdbc ? view answer
Q. What is lazy fetching in Hibernate? With Example . view answer
Q.what is the advantage of Hibernate over jdbc? view answer
How to Integrate Struts Spring Hibernate ? view answer
How to prevent concurrent update in Hibernate? view answer
How to perevent slate object updatation in Hibernate ? view answer
What is version checking in Hibernate ? view answer
How to handle user think time using hibernate ? view answer
Q.Transaction with plain JDBC in Hibernate ? view answer
Q.What are the general considerations or best practices for defining your Hibernate persistent classes? view answer
Q.Difference between session.update() and session.lock() in Hibernate ? view answer
Q.Difference between getCurrentSession() and openSession() in Hibernate ? view answer
Difference between session.saveOrUpdate() and session.merge()? view answer
Filter in Hibernate with Example? view answer
Q.How does Value replacement in Message Resource Bundle work? view answer
Difference between list() and iterate() i9n Hibernate? view answer
Difference between session.load() and session.get() ? view answer
Deleting persistent objects view answer
SQL statements execution order. view answer
Difference between session.saveOrUpdate() and session.merge(); view answer
Modifying persistent objects? view answer
SQL Queries In Hibernate.. view answer
Filter in Hibernate view answer
Criteria Query Two Condition view answer
Equal and Not Equal criteria query. view answer
Cascade Save or Update in Hibernate ? view answer
One To Many Bi-directional Relation in Hibernate? view answer
One To Many Mapping Using List ? view answer
Many To Many Relation In Hibernate ? view answer
What does session.refresh() do ? view answer
Difference between session.load() and session.get()? view answer
Hibernate setup using .cfg.xml file ? view answer
How to add .hbm.xml file in sessionFactory? view answer
How to get Hibernate statistics ? view answer
How to set 2nd level cache in hibernate with EHCache? view answer
How to get JDBC connections in hibernate? view answer
How will you configure Hibernate? view answer
How to create Session and SessionFactory in Hibernate? view answer
What are the Instance states in Hibernate? view answer
What are the core components in Hibernate ? view answer
What is a Hibernate Session? Can you share a session object between different theads? view answer
addScalar() method in hibernate... view answer
Hibernate session.close does _not_ call session.flush ? view answer
What is the main difference between Entity Beans and Hibernate ? view answer
Difference between session.save() and session.saveOrUpdate()? view answer
How are joins handled using Hinernate. view answer
What is Hibernate proxy? view answer
What is the main advantage of using the hibernate than using the sql ? view answer
how to create primary key using hibernate? view answer
what is the advantage of Hibernate over jdbc? view answer
How to Execute Stored procedure in Hibernate ? view answer
what is lazy fetching in hibernate? view answer
This is the default fetching strategy. it enabled the lazy loading of all it’s related collections. Let see the example…
Join fetching: Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER
JOIN.
Select fetching: a second SELECT is used to retrieve the associated entity or collection. Unless you
explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when
you access the association.
Subselect fetching: a second SELECT is used to retrieve the associated collections for all entities retrieved
in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this
second select will only be executed when you access the association.
Batch fetching: an optimization strategy for select fetching. Hibernate retrieves a batch of entity instances
or collections in a single SELECT by specifying a list of primary or foreign keys.
Hibernate also distinguishes between:
Immediate fetching: an association, collection or attribute is fetched immediately when the owner is loaded.
Lazy collection fetching: a collection is fetched when the application invokes an operation upon that
collection. This is the default for collections.
"Extra-lazy" collection fetching: individual elements of the collection are accessed from the database as
needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed. It is
suitable for large collections.
Proxy fetching: a single-valued association is fetched when a method other than the identifier getter is
invoked upon the associated object.
"No-proxy" fetching: a single-valued association is fetched when the instance variable is accessed. Compared
to proxy fetching, this approach is less lazy; the association is fetched even when only the identifier is
accessed. It is also more transparent, since no proxy is visible to the application. This approach requires
buildtime bytecode instrumentation and is rarely necessary.
Lazy attribute fetching: an attribute or single valued association is fetched when the instance variable is
accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.
We have two orthogonal notions here: when is the association fetched and how is it fetched. It is important
that you do not confuse them. We use fetch to tune performance. We can use lazy to define a contract for what
data is always available in any detached instance of a particular class.