0% found this document useful (0 votes)
10 views

Hibernate notes

Hibernate notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Hibernate notes

Hibernate notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Hibernate

1.What is ORM ?
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java
application to the tables in a relational database.

2.What does ORM consists of ?


An ORM solution consists of the followig four pieces:
● API for performing basic CRUD operations
● API to express queries refering to classes
● Facilities to specify metadata
● Optimization facilities : dirty checking,lazy associations fetching
3.What are the ORM levels ?
The ORM levels are:
● Pure relational (stored procedure.)
● Light objects mapping (JDBC)
● Medium object mapping
● Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)
4.What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you
to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is
to relieve the developer from a significant amount of relational data persistence-related programming
tasks.

5.Why do you need ORM tools like hibernate?


The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from
this, ORM provides following benefits:
● Improved productivity
○ High-level object-oriented API
○ Less Java code to write
○ No SQL to write
● Improved performance
○ Sophisticated caching
○ Lazy loading
○ Eager loading
● Improved maintainability
○ A lot less code to write
● Improved portability
○ ORM framework generates database-specific SQL for you
6.What Does Hibernate Simplify?
Hibernate simplifies:
● Saving and retrieving your domain objects
● Making database column and table name changes
● Centralizing pre save and post retrieve logic
● Complex joins for retrieving related items
● Schema creation from object model

10.What are the Core interfaces are of Hibernate framework?


The five core interfaces are used in just about every Hibernate application. Using these
interfaces, you can store and retrieve persistent objects and control transactions.
● Session interface
● SessionFactory interface
● Configuration interface
● Transaction interface
● Query and Criteria interfaces
11.What role does the Session interface play in Hibernate?
The Session interface is the primary interface used by Hibernate applications. It is a single-
threaded, short-lived object representing a conversation between the application and the
persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();


Session interface role:
● Wraps a JDBC connection
● Factory for Transaction
● Holds a mandatory (first-level) cache of persistent objects, used when navigating the
object graph or looking up objects by identifier
12.What role does the SessionFactory interface play in Hibernate?
The application obtains Session instances from a SessionFactory. There is typically a single
SessionFactory for the whole applicationå¹¼reated during application initialization. The
SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses
at runtime. It also holds cached data that has been read in one unit of work and may be reused in a
future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

13.What is the general flow of Hibernate communication with RDBMS?


The general flow of Hibernate communication with RDBMS is :
● Load the Hibernate configuration file and create configuration object. It will automatically
load all hbm mapping files
● Create session factory from configuration object
● Get one session from this session factory
● Create HQL Query
● Execute query to get list containing Java objects
14.What is Hibernate Query Language (HQL)?
Hibernate offers a query language that embodies a very powerful and flexible mechanism to query,
store, update, and retrieve objects from a database. This language, the Hibernate query Language
(HQL), is an object-oriented extension to SQL.

15.How do you map Java Objects with Database tables?


● First we need to write Java domain objects (beans with setter and getter).
● Write hbm.xml, where we map java class to table and database columns to Java class
variables.
Example :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>

16.What’s the difference between load() and get()?


load() vs. get() :-

load() get()

Only use the load() method if you are sure that the If you are not sure that the object exists,
object exists. then use one of the get() methods.

load() method will throw an exception if the get() method will return null if the
unique id is not found in the database. unique id is not found in the database.

load() just returns a proxy by default and database get() will hit the database immediately.
won’t be hit until the proxy is first invoked.

17.What is the difference between and merge and update ?


Use update() if you are sure that the session does not contain an already persistent instance with
the same identifier, and merge() if you want to merge your modifications at any time without
consideration of the state of the session.

18.How do you define sequence generated primary key in hibernate?


Using <generator> tag.
Example:-
<id column="USER_ID" name="id" type="java.lang.Long">
<generator class="sequence">
<param name="table">SEQUENCE_NAME</param>
<generator>
</id>

19.Define cascade and inverse option in one-many mapping?


cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.


inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a
parent who has a collection of children, should you ask the parent for its list of children, or ask the
children who the parents are?

20.What do you mean by Named – SQL query?


Named SQL queries are defined in the mapping xml document and called wherever required.
Example:
<sql-query name = "empdetails">
<return alias="emp" class="com.test.Employee"/>
SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>

Invoke Named Query :


List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();

21.How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true">


<return alias="emp" class="employee">
<return-property name="empid" column="EMP_ID"/>

<return-property name="name" column="EMP_NAME"/>


<return-property name="address" column="EMP_ADDRESS"/>
{ ? = call selectAllEmployees() }
</return>
</sql-query>

22.Explain Criteria API


Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very
convenient approach for functionality like "search" screens where there is a variable number of
conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();

23.Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides
different methods for querying/retrieving data from the database. It also converts checked
HibernateExceptions into unchecked DataAccessExceptions.

24.What are the benefits does HibernateTemplate provide?


The benefits of HibernateTemplate are :
● HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
● Common functions are simplified to single method calls.
● Sessions are automatically closed.
● Exceptions are automatically caught and converted to runtime exceptions.

25.How do you switch between relational databases without code changes?


Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql
queries based on the dialect defined.

26.If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>

27.What are derived properties?


The properties that are not mapped to a column, but calculated at runtime by evaluation of
an expression are called derived properties. The expression can be defined using the formula
attribute of the element.

28.What is component mapping in Hibernate?


● A component is an object saved as a value, not as a reference
● A component can be saved directly without needing to declare interfaces or identifier
properties
● Required to define an empty constructor
● Shared references not supported
29.What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :-

sorted collection order collection

A sorted collection is sorting a collection by Order collection is sorting a collection by


utilizing the sorting features provided by specifying the order-by clause for sorting this
the Java collections framework. The sorting collection when retrieval.
occurs in the memory of JVM which running
Hibernate, after the data being read from
database using java comparator.

If your collection is not large, it will be more If your collection is very large, it will be more
efficient way to sort it. efficient way to sort it .

31.What is the advantage of Hibernate over jdbc?


Hibernate Vs. JDBC :-

JDBC Hibernate

With JDBC, developer has to Hibernate is flexible and


write code to map an object powerful ORM solution to map
model's data representation to Java classes to database tables.
a relational data model and its Hibernate itself takes care of
corresponding database schema. this mapping using XML files
so developer does not need to
write code for this.
With JDBC, the automatic Hibernate provides transparent
mapping of Java objects with persistence and developer
database tables and vice versa does not need to write code
conversion is to be taken care explicitly to map database
of by the developer manually tables tuples to application
with lines of code. objects during interaction with
RDBMS.

JDBC supports only native Hibernate provides a powerful


Structured Query Language query language Hibernate
(SQL). Developer has to find Query Language (independent
out the efficient way to access from type of database) that is
database, i.e. to select effective expressed in a familiar SQL like
query from a number of queries syntax and includes full support
to perform same task. for polymorphic queries.
Hibernate also supports native
SQL statements. It also selects
an effective way to perform a
database manipulation task for
an application.

Application using JDBC Hibernate provides this mapping


to handle persistent data itself. The actual mapping
(database tables) having between tables and application
database specific code in large objects is done in XML files. If
amount. The code written to there is change in Database or
map table data to application in any table then the only need
objects and vice versa is to change XML file properties.
actually to map table fields
to object properties. As table
changed or database changed
then it’s essential to change
object structure as well as to
change code written to map
table-to-object/object-to-table.

With JDBC, it is developer’s Hibernate reduces lines of code


responsibility to handle JDBC by maintaining object-table
result set and convert it to Java mapping itself and returns result
objects through code to use this to application in form of Java
persistent data in application. objects. It relieves programmer
So with JDBC, mapping between from manual handling of
Java objects and database persistent data, hence reducing
tables is done manually. the development time and
maintenance cost.
With JDBC, caching is Hibernate, with Transparent
maintained by hand-coding. Persistence, cache is set
to application work space.
Relational tuples are moved to
this cache as a result of query.
It improves performance if
client application reads same
data many times for same
write. Automatic Transparent
Persistence allows the
developer to concentrate more
on business logic rather than
this application code.

In JDBC there is no check that Hibernate enables developer


always every user has updated to define version type field to
data. This check has to be application, due to this defined
added by the developer. field Hibernate updates version
field of database table every
time relational tuple is updated
in form of Java class object
to that table. So if two users
retrieve same tuple and then
modify it and one user save this
modified tuple to database,
version is automatically updated
for this tuple by Hibernate.
When other user tries to save
updated tuple to database
then it does not allow saving it
because this user does not have
updated data.

32.What are the Collection types in Hibernate ?


● Bag
● Set
● List
● Array
● Map

33.What are the ways to express joins in HQL?


HQL provides four ways of expressing (inner and outer) joins:-
● An implicit association join
● An ordinary join in the FROM clause
● A fetch join in the FROM clause.
● A theta-style join in the WHERE clause.

Different Hibernate Joins

Inner Join
1.
List<Object[]> africanContinents = session.createQuery(
"from Continent cont join cont.countries ctry " +
"where cont.name = 'Africa'")
.list();

Query
select
COUNTRY.CTRY_ID,
COUNTRY.AREA,
CONTINENT.CONT_ID,
CONTINENT.CONT_NAME,
COUNTRY.CURRENCY,
COUNTRY.CTRY_NAME,
COUNTRY.POP,
COUNTRY.POP_UPD_ON
from
CONTINENT
inner join
COUNTRY
on CONTINENT.CONT_ID=COUNTRY.CONT_ID
where
CONT_NAME='Africa'

2.
List<String> continentsWithBigCountries = session.createQuery(
"select distinct cont.name " +
"from Continent cont join cont.countries ctry " +
"where ctry.area > 100000")
.list();

Query
select
distinct CONT_NAME
from
CONTINENT
inner join
COUNTRY
on CONTINENT.CONT_ID=COUNTRY.CONT_ID
where
AREA>100000

Outer Join
1.
List<Object[]> allContinentsAndCountries = session.createQuery(
"select cont.name, nvl(ctry.name, '[none]') " +
"from Continent cont left join cont.countries ctry " +
"with ctry.area > 100000 " +
"order by cont.name")
.list();

select
CONT_NAME,
nvl(CTRY_NAME, '[none]')
from
CONTINENT
left outer join
COUNTRY
on CONTINENT.CONT_ID=COUNTRY.CONT_ID
and (
AREA>100000
)
order by
CONT_NAME

3.Theta-Style Joins
Theta-style joins use a more traditional join syntax by specifying a comma separated list of
classes in the from clause and the join condition in thewhere clause.

This query returns any continents that share a name with a country:
List<Continent> sameNames = session.createQuery(
"select cont " +
"from Continent cont, Country ctry " +
"where cont.name = ctry.name")
.list();
The from and where clauses are almost identical in the generated SQL.
select
CONTINENT.CONT_ID,
CONTINENT.CONT_NAME
from
CONTINENT,
COUNTRY
where
CONTINENT.CONT_NAME=COUNTRY.CTRY_NAME
The main reason to use theta-style syntax is to specify a join that is not mapped with an
association.

4.Fetch

Fetch
Suppose we retrieve a Continent object using HQL knowing that we will be accessing the
Country objects that belong to that Continent. We join to the Country class to retrieve the
data in one SQL statement.
Continent europe = (Continent) session.createQuery(
"select cont " +
"from Continent cont join cont.countries " +
"where cont.name = 'Europe'")
.uniqueResult();
The uniqueResult() method generates SQL which includes a join to the COUNTRY table.
select
CONTINENT.CONT_ID,
CONTINENT.CONT_NAME
from
CONTINENT
inner join
COUNTRY
on CONTINENT.CONT_ID=COUNTRY.CONT_ID
where
CONT_NAME='Europe'
However, if we take a look at the select clause, we can see that no Country data has been
returned.
Now suppose we wish to see the number of countries in Europe.

europe.getCountries().size()

When we run this statement, the following SQL is triggered:


select
CTRY_ID,
AREA,
CONT_ID,
CURRENCY,
CTRY_NAME,
POP,
POP_UPD_ON
from
COUNTRY
where
CONT_ID=?
The join to cont.countries in the first SQL statement appears to be redundant. This is
because, by default, Hibernate returns a proxy for theCountry objects.

To eagerly fetch the Country objects using a single SQL statement, add the fetch keyword to
the HQL query.
Continent europe = (Continent) session.createQuery(
"select cont " +
"from Continent cont join fetch cont.countries " +
"where cont.name = 'Europe'")
.uniqueResult();
This time, the following SQL is generated by uniqueResult() and all the objects are
populated in the countries collection, immediately:
select
CONTINENT.CONT_ID,
COUNTRY.CTRY_ID ,
CONTINENT.CONT_NAME,
COUNTRY.AREA,
COUNTRY.CURRENCY,
COUNTRY.CTRY_NAME,
COUNTRY.POP,
COUNTRY.POP_UPD_ON
from
CONTINENT
inner join
COUNTRY
on CONTINENT.CONT_ID=COUNTRY.CONT_ID
where
CONT_NAME='Europe'
The getCountries().size() method now accesses the in memory list without executing any
further SQL.

My Analysis On HQL
HQL
select con , adr from com.ebix.sosync.domain.Contact as con
join con.addresses adr
where con.contactId < 1000

select
<<contact all fields , address all fields>>
from
Contact contact0_
inner join
Address addresses1_
on contact0_.contactId=addresses1_.CONTACTID
where
contact0_.contactId<1000

SO When we use join internally used join is inner join

2.
select con , adr from com.ebix.sosync.domain.Contact as con
left join con.addresses adr
where con.contactId < 1000

Query
select
<<All contact and Address fileds>>
Contact contact0_
left outer join
Address addresses1_
on contact0_.contactId=addresses1_.CONTACTID
where
contact0_.contactId<1000

So when we use Left Join internally Hibernate converts it into left outer
join
When we use fetch the Hibernate will internally Fetch All the records from
the join table

Question from JavaRevisited

Difference between get and load in Hibernate


get vs load in Hibernate

Difference between get and load method in Hibernate is a one of the most popular question asked in
Hibernate and spring interviews. Hibernate Session class provides two method to access object e.g.
session.get() and session.load() both looked quite similar to each other but there are subtle difference
between load and get method which can affect performance of application. Main difference between get() vs
load method is that get() involves database hit if object doesn't exists in Session Cache and returns a fully
initialized object which may involve several database call while load method can return proxy in place and
only initialize the object or hit the database if any method other than getId() is called on persistent or entity
object. This lazy initialization can save couple of database round-trip which result in better performance.

Difference between get and load method


Here are few differences between get and load method in Hibernate.

1. Behavior when Object is not found in Session Cache


Apart from performance this is another difference between get and load which is worth remembering. get method
of Hibernate Session class returns null if object is not found in cache as well as on database while load() method
throws ObjectNotFoundException if object is not found on cache as well as on database but never return null.

2. Database hit
Get method always hit database while load() method may not always hit the database, depending upon which
method is called.

3. Proxy
Get method never returns a proxy, it either returns null or fully initialized Object, while load() method may return
proxy, which is the object with ID but without initializing other properties, which is lazily initialized. If you are just using
returned object for creating relationship and only need Id then load() is the way to go.

4. Performance
By far most important difference between get and load in my opinion. get method will return a completely
initialized object if Object is not on the cache but exists on Database, which may involve multiple round-trips
to database based upon object relational mappings while load() method of Hibernate can return a proxy which
can be initialized on demand (lazy initialization) when a non identifier method is accessed. Due to above reason
use of load method will result in slightly better performance, but there is a caveat that proxy object will throw
ObjectNotFoundException later if corresponding row doesn’t exists in database, instead of failing immediately
so not a fail fast behavior.

5. load method exists prior to get method which is added on user request.

When to use Session get() and load() in Hibernate


So far we have discussed how get and load are different to each other and how they can affect performance of
your web application, after having this information in our kitty we can see some best practices to get most of load
and get together. This section suggest some scenario which help you when to use get and load in Hibernate.

1. Use get method to determine if an instance exists or not because it can return null if instance doesn’t exists in
cache and database and use load method to retrieve instance only if you think that instance should exists and non
availability is an error condition.

2. As stated in difference number 2 between get and load in Hibernate. get() method could suffer performance
penalty if only identifier method like getId() is accessed. So consider using load method if your code doesn't
access any method other than identifier or you are OK with lazy initialization of object, if persistent object is not in
Session Cache because load() can return proxy.

How to call get records in Hibernate using get and load method
If you look at below code , there is not much difference on calling get() and load() method, though both are
overloaded now and can accept few more parameters but the primary methods looks exactly identical. It’s there
behavior which makes them different.

//Example of calling get method of Hiberante Session class


Session session = SessionFactory.getCurrentSession();
Employee Employee = (Employee) session.get(Employee.class, EmployeeID);

//Example of calling load method of Hiberante Session


Session session = SessionFactory.getCurrentSession();
Employee Employee = (Employee) session.load(Employee.class, EmployeeID);

That’s all on difference between get and load in Hibernate. No doubt Hibernate is a great tool for Object relational
mapping but knowing this subtle differences can greatly help to improver performance of your J2EE application, apart
from practical reason get vs load method is also frequently asked questions in Hibernate interview, so familiarity with
differences between load and get certainly helps.

Difference between save and saveOrUpdate in Hibernate


Main difference between save and saveOrUpdate method is that save() generates a new identifier and
INSERT record into database while saveOrUpdate can either INSERT or UPDATE based upon existence
of record. Clearly saveOrUpdate is more flexible in terms of use but it involves an extra processing to find
out whether record already exists in table or not. In summary save() method saves records into database
by INSERT SQL query, Generates a new identifier and return the Serializable identifier back. On the other
hand saveOrUpdate() method either INSERT or UPDATE based upon existence of object in database. If
persistence object already exists in database then UPDATE SQL will execute and if there is no corresponding
object in database than INSERT will run.

Difference between save and persist method in Hibernate


1)First difference between save and persist is there return type. Similar to save method persist also INSERT
records into database but return type of persist is void while return type of save is Serializable object.

2) Another difference between persist and save is that both methods make a transient instance persistent.
However, persist() method doesn't guarantee that the identifier value will be assigned to the persistent
instance immediately, the assignment might happen at flush time.

3) One more thing which differentiate persist and save method in Hibernate is that is there behavior on outside of
transaction boundaries. persist() method guarantees that it will not execute an INSERT statement if it is called
outside of transaction boundaries. save() method does not guarantee the same, it returns an identifier, and if an
INSERT has to be executed to get the identifier (e.g. "identity" generator), this INSERT happens immediately, no
matter if you are inside or outside of a transaction.

4) Fourth difference between save and persist method in Hibernate is related to previous difference on save vs
persist. Because of its above behavior of persist method outside transaction boundary, its useful in long-running
conversations with an extended Session context. On the other hand save method is not good in a long-running
conversation with an extended Session context.

What is named SQL query in Hibernate?

This Hibernate Interview question is related to query functionality provided by Hibernate. Named queries
are SQL queries which are defined in mapping document using <sql-query> tag and called using
Session.getNamedQuery() method. Named query allows you to refer a particular query by the name you
provided, by the way you can define named query in hibernate either by using annotations or xml mapping file, as
I said above. @NameQuery is used to define single named query and @NameQueries is used to define multiple
named query in hibernate.

What is named SQL query in Hibernate?

This Hibernate Interview question is related to query functionality provided by Hibernate. Named queries
are SQL queries which are defined in mapping document using <sql-query> tag and called using
Session.getNamedQuery() method. Named query allows you to refer a particular query by the name you
provided, by the way you can define named query in hibernate either by using annotations or xml mapping file, as
I said above. @NameQuery is used to define single named query and @NameQueries is used to define multiple
named query in hibernate.
What is SessionFactory in Hibernate? is SessionFactory thread-safe?

Another common Interview questions related to Hibernate framework. SessionFactory as name suggest
is a factory to create hibernate Session objects. SessionFactory is often built during start-up and used by
application code to get session object. It acts as single data store and its also thread-safe so that multiple thread
can use same SessionFactory. Usually a Java JEE application has just one SessionFactory, and individual
threads, which are servicing client’s request obtain hibernate Session instances from this factory, that’s why any
implementation of SessionFactory interface must be thread-safe. Also internal state ofSessionFactory,
which contains all meta data about Object/Relational mapping is Immutable and can not be changed once created.

What is Session in Hibernate? Can we share single Session among multiple threads in Hibernate?

This is usually asked as follow-up question of previous Hibernate Interview question. After SessionFactory its
time for Session. Session represent a small unit of work in Hibernate, they maintain connection with database
and they are not thread-safe, it means you can not share Hibernate Session between multiple threads. Though
Session obtains database connection lazily it's good to close session as soon as you are done with it.

What is difference between sorted and ordered collection in hibernate?

This is one of the easy Hibernate interview question you ever face. A sorted collection is sorted in memory by
using Java Comparator, while a ordered collection uses database's order by clause for ordering. For large data
set it's better to use ordered collection to avoid any OutOfMemoryError in Java, by trying to sort them in memory.

What is difference between transient, persistent and detached object in Hibernate?

In Hibernate, Object can remain in three state transient, persistent or detached. An object which is
associated with Hibernate session is called persistent object. Any change in this object will reflect in database
based upon your flush strategy i.e. automatic flush whenever any property of object change or explicit flushing
by calling Session.flush() method. On the other hand if an object which is earlier associated with Session,
but currently not associated with it are called detached object. You can reattach detached object to any other
session by calling either update() or saveOrUpdate() method on that session. Transient objects are newly
created instance of persistence class, which is never associated with any Hibernate Session. Similarly you can
call persist() or save() methods to make transient object persistent. Just remember, here transient doesn’t
represent transient keyword in Java, which is altogether different thing.

What does Session lock() method do in Hibernate?

This one is one of the tricky Hibernate Interview question, because Session's lock() method reattach object
without synchronizing or updating with database. So you need to be very careful while using lock() method. By
the way you can always use Session's update() method to sync with database during reattachment. Some time
this Hibernate question is also asked as what is difference between Session's lock() and update() method. You can
use this key point to answer that question as well.

What is Second level Cache in Hibernate?

This is one of the first interview question related to caching in Hibernate, you can expect few more. Second level
Cache is maintained at SessionFactory level and can improve performance by saving few database round trip.
Another worth noting point is that second level cache is available to whole application rather than any particular
session.

What is query cache in Hibernate ?


This question, Some times asked as a follow-up of last Hibernate Interview question, QueryCache actually
stores result of sql query for future calls. Query cache can be used along with second level cache for improved
performance. Hibernate support various open source caching solution to implement Query cache e.g. EhCache.

Why it's important to provide no argument constructor in Hibernate Entities?

Every Hibernate Entity class must contain a no argument constructor, because


Hibernate framework creates instance of them using Reflection API, by calling
Class.newInstance() method. This method will throw InstantiationException if
it doesn't found no argument constructor inside Entity class.

Can we make an Hibernate Entity Class final?

Yes, you can make an Hibernate Entity class final, but that's not a good practice. Since
Hibernate uses proxy pattern for performance improvement in case of lazy association,
by making an entity final, Hibernate will no longer be able to use proxy, because Java
doesn't allow extension of final class, thus limiting your performance improvement options.
Though, you can avoid this penalty, if your persistent class is an implementation of
interface, which declares all public methods defined in Entity class.

You might also like