Q.1 What is Hibernate?
Ans.
Synonym
of Hibernate is Winter. It means Spend the winter in a dormant state.
As a
technology Hibernate is a open source, free Java package that makes it easy to
work with relational databases. It 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.
Q2. What is ORM?
Ans. ORM stands for Object/Relational mapping. It is the
programmed and mapping of objects in a Java application in to the tables of a
relational database using the meta data that describes the mapping between
the objects and the database. It works by transforming the data from one
representation to another.
We are
familiar with model/pojo class and Relational
database. Here Object means Mode/Pojo class and Relational means the databases.
By hbm.xml file we represent the mapping between Object and Relational
databases.
Q 3.
What does an ORM solution comprises of?
Ans. Hibernate should have an language or API for performing
basic CRUD (Create, Read, Update, Delete) operations on objects of persistent
classes where persistent means POJO classes that you create that represent the table in database to keep
the state of object alive.
It
should have a language or an API for specifying queries that refer to the
classes and the properties of classes an ability for specifying mapping
metadata.
It
should have a technique for ORM implementation to interact with transactional
objects to perform lazy association fetching, dirty checking, and other optimization
functions.
Q4.
What are the different levels of ORM quality?
Ans. Four levels defined for ORM quality:
- Pure relational
- Light object mapping
- Medium object mapping
- Full object mapping
·
Pure relational:
·
The entire application, including the user interface, designed
around the relational model and SQL based relational operations.
·
Light object mapping :
·
The entities are represented as classes that are mapped manually
to the relational tables. The code is hidden from the business logic using
specific design patterns. This approach is successful for applications with a
less number of entities, or applications with common, metadata-driven data
models.
·
Medium object mapping:
·
The application is designed around an object model. The SQL code
is generated at build time. And the associations between objects are supported
by the persistence mechanism, and queries are specified using an
object-oriented expression language. This is best suited for medium-sized applications
with some complex transactions.
·
Full object mapping:
·
Full object mapping supports sophisticated object modeling:
inheritance, polymorphism, composition and persistence. The persistence layer
implements transparent persistence. Persistent classes do not inherit any
special base class or have to implement a special interface. Efficient fetching
strategies and caching strategies are implemented transparently to the
application.
Q5. Why do you need ORM tools like hibernate?
Ans. 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
* Eager loading
► Improved maintainability
* A lot less code to write
► Improved portability
* ORM framework generates database-specific SQL for you
► Improved productivity
* High-level object-oriented API
* Less Java code to write
* No SQL to write
► Improved performance
* Sophisticated caching
* Eager loading
► Improved maintainability
* A lot less code to write
► Improved portability
* ORM framework generates database-specific SQL for you
Q6. What are the
benefits of ORM and Hibernate?
Ans. There are many benefits from these. Out of which the
following are the most important one.
Productivity : Hibernate reduces the burden of developer by providing
much of the functionality and let the developer to concentrate on business
logic.
Maintainability :As hibernate provides most of the functionality, the LOC for
the application will be reduced and it is easy to maintain. By automated
object/relational persistence it even reduces the LOC.
Performance : Hand-coded persistence provided greater performance
than automated one. But this is not true all the times. But in hibernate, it
provides more optimization that works all the time there by increasing the
performance. If it is automated persistence then it still increases the
performance.
Vendor independence : Irrespective of the different types of databases that
are there, hibernate provides a much easier way to develop a cross platform
application.
Q7.What is difference
between Difference
between save(), saveOrUpdate() and persist() in Hibernate Session
Session interface
in Hibernate provides a couple of methods to move an object from new or
transient state to persistent state e.g. save(), saveOrUpdate() and persist() are used to store an object into the
database, but there are some significant differences between them. The Session.save() method
does an INSERT to store the object into the database and it also return the
identifier generated by the database. On the other hand, saveOrUpdate() can
be used to reattach a detached object in Hibernate Session i.e. it can do
INSERT or UPDATE depending upon whether object exists in database or not. The
third method, persist() is similar to Session.save() i.e. it is used to move a
transient object to the persistent state by storing it into the database but it
doesn't return the database identifier. This was the basic difference between save() vs saveOrUpdate() vs persist() method
and suggest when to use which method. It is also one of the frequently asked
Hibernate interview questions on Java Web developer job interviews. Knowing
this detail help you to do well on your interview. Btw, if you have not read
already then you must read Java Persistence with Hibernate, best
book to learn these kinds of subtle details about Hibernate.
Session.save()
vs Session.saveOrUpdate() vs Session.Persist
As I said, all three methods save(), persist() and
saveOrUpdate belongs to Hibernate's Session interface. They all are used to
bring a new object into persistence context or a detached object, which was
associated with a Hibernate Session in past but currently it's not associated
into active persistence context. It is also one of the most popular Hibernate interview questions. Let's
see couple of more differences between save(), persist() and saveOrUpdate()
methods of Session interface
1.1) The main difference between save() and saveOrUpdate() method is that save() method performs an INSERT operation to store
the object into the database, but INSERT will fail if the primary key is
already persistent i.e. object already exists in the database. This is why, you
should only call save() with an absolutely new object which doesn't have any
database identifier. Calling save() with the detached object will fail. This is
opposite of saveOrUpdate() method,
which can do either INSERT or UPDATE SQL query depending upon whether an object
exists in the database or not. The saveOrUpdate() method first executes a SELECT query to
determine if it needs to do an INSERT or UPDATE operation.
1.2) Another key difference between save() and
saveOrUpdate() method is that former is used to bring a transient
object to persistent
state but saveOurUpdate() can bring
both transient (new) and detached (existing) object into persistent state. It
is often used to re-attach a detached object into Session.
Here is an object's lifecycle and state
transition diagram in Hibernate which shows that save() and saveOrUpdate() can move an object from transient to
persistent state.

1.3) Coming to persist() method, the difference between save() and persist()
method is that former returns the generated database identifier, a Serializable object but persist() method
doesn't return anything. It's return type is void.
For example:
System.out.println(session.save(aCoin));
will print the generated primary key, but the
following line will throw a compile time error because persist()'s
return type is void.
System.out.println(session.persist(aCoin));
That's all about difference
between save(), saveOrUpdate() and persist() method of Hibernate Session
interface. Now you know the basic difference
between them and also learned when to use the save(), saveOrUpdate() and
persist() method. Use the save() method to store new object into database and
when you need the generated database identifier, otherwise use persist()
method. You can use saveOrUpdate() to reattach a detached object into Hibernate
Session.
Q.8. What is the difference between get and load in Hibernate?
get vs load is one of the most frequently asked Hibernate
Interview question, since correct understanding of both get() and load() is
require to effectively using Hibernate. Main difference between get and load is
that, get will hit the database if object is not found in the cache and
returned completely initialized object, which may involve several database call
while load() method
can return proxy, if object is not found in cache and only hit database if any
method other than getId() is
called. This can save a lot of performance in some cases.
Q.9 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.
Q.10. What is SessionFactory in Hibernate? is SessionFactory
thread-safe?
Another common Interview questions related to Hibernate
framework. SessionFactory, as the
name suggest, is a factory to hibernate Session objects. SessionFactory is often built during start-up and
used by application code to get session object. It acts as a single data store
and it's also thread
safe so that multiple threads can use the 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, the internal state of SessionFactory, which contains all
metadata about Object/Relational mapping is immutable and can not be
changed once created.
Q.11 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 a
connection with the 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.
Q.12 What is the difference
between sorted and ordered collection in hibernate?
This is one of the easy Hibernate interview questions you ever
face. A sorted collection is sorted in memory by using java comprator while an ordered
collection uses database's order
by clause for ordering. For large data set it's better to use
ordered collection to avoid any Out of memory in
java, by trying to sort them in memory.
Q.13 What is the difference between transient, a 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 the database based on 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 have newly created an instance of
persistence class, which is never associated with any Hibernate Session.
Similarly, you can call persist() or save() methods to make a transient object persistent. Just
remember, here transient doesn’t represent transient keyword in jav, which is
an altogether different thing.
Q14. What is hibernate
configuration file?.
Hibernate
requires to know in advance where to find the mapping information that defines
how your Java classes relate to the database tables. Hibernate also requires a
set of configuration settings related to database and other related parameters.
All such information is usually supplied as a standard Java properties file
called hibernate.properties, or as an XML file named hibernate.cfg.xml.
I will
consider XML formatted file hibernate.cfg.xml to specify
required Hibernate properties in my examples. Most of the properties take their
default values and it is not required to specify them in the property file
unless it is really required. This file is kept in the root directory of your
application's classpath.
Hibernate Properties:
Following
is the list of important properties you would require to configure for a
databases in a standalone situation:
Productivity : Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.
Maintainability :As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.
Performance : Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance.
Vendor independence : Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.
Session interface in Hibernate provides a couple of methods to move an object from new or transient state to persistent state e.g. save(), saveOrUpdate() and persist() are used to store an object into the database, but there are some significant differences between them. The Session.save() method does an INSERT to store the object into the database and it also return the identifier generated by the database. On the other hand, saveOrUpdate() can be used to reattach a detached object in Hibernate Session i.e. it can do INSERT or UPDATE depending upon whether object exists in database or not. The third method, persist() is similar to Session.save() i.e. it is used to move a transient object to the persistent state by storing it into the database but it doesn't return the database identifier. This was the basic difference between save() vs saveOrUpdate() vs persist() method and suggest when to use which method. It is also one of the frequently asked Hibernate interview questions on Java Web developer job interviews. Knowing this detail help you to do well on your interview. Btw, if you have not read already then you must read Java Persistence with Hibernate, best book to learn these kinds of subtle details about Hibernate.
1.1) The main difference between save() and saveOrUpdate() method is that save() method performs an INSERT operation to store the object into the database, but INSERT will fail if the primary key is already persistent i.e. object already exists in the database. This is why, you should only call save() with an absolutely new object which doesn't have any database identifier. Calling save() with the detached object will fail. This is opposite of saveOrUpdate() method, which can do either INSERT or UPDATE SQL query depending upon whether an object exists in the database or not. The saveOrUpdate() method first executes a SELECT query to determine if it needs to do an INSERT or UPDATE operation.
1.2) Another key difference between save() and saveOrUpdate() method is that former is used to bring a transient object to persistent state but saveOurUpdate() can bring both transient (new) and detached (existing) object into persistent state. It is often used to re-attach a detached object into Session.
Here is an object's lifecycle and state transition diagram in Hibernate which shows that save() and saveOrUpdate() can move an object from transient to persistent state.

1.3) Coming to persist() method, the difference between save() and persist() method is that former returns the generated database identifier, a Serializable object but persist() method doesn't return anything. It's return type is void.
For example:
will print the generated primary key, but the following line will throw a compile time error because persist()'s return type is void.
That's all about difference between save(), saveOrUpdate() and persist() method of Hibernate Session interface. Now you know the basic difference between them and also learned when to use the save(), saveOrUpdate() and persist() method. Use the save() method to store new object into database and when you need the generated database identifier, otherwise use persist() method. You can use saveOrUpdate() to reattach a detached object into Hibernate Session.
Q.9 What is named SQL query in Hibernate?
Q.10. What is SessionFactory in Hibernate? is SessionFactory thread-safe?
Q.12 What is the difference between sorted and ordered collection in hibernate?
Q.13 What is the difference between transient, a persistent and detached object in Hibernate?
You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on that session. Transient objects have newly created an instance of persistence class, which is never associated with any Hibernate Session. Similarly, you can call persist() or save() methods to make a transient object persistent. Just remember, here transient doesn’t represent transient keyword in jav, which is an altogether different thing.
S.N.
|
Properties
and Description
|
1
|
hibernate.dialect
This property makes Hibernate generate the appropriate SQL for the chosen database. |
2
|
hibernate.connection.driver_class
The JDBC
driver class.
|
3
|
hibernate.connection.url
The
JDBC URL to the database instance.
|
4
|
hibernate.connection.username
The
database username.
|
5
|
hibernate.connection.password
The
database password.
|
6
|
hibernate.connection.pool_size
Limits
the number of connections waiting in the Hibernate database connection pool.
|
7
|
hibernate.connection.autocommit
Allows
autocommit mode to be used for the JDBC connection.
|
If you
are using a database along with an application server and JNDI then you would
have to configure the following properties:
S.N.
|
Properties
and Description
|
1
|
hibernate.connection.datasource
The
JNDI name defined in the application server context you are using for the
application.
|
2
|
hibernate.jndi.class
The
InitialContext class for JNDI.
|
3
|
hibernate.jndi.<JNDIpropertyname>
Passes
any JNDI property you like to the JNDI InitialContext.
|
4
|
hibernate.jndi.url
Provides
the URL for JNDI.
|
5
|
hibernate.connection.username
The
database username.
|
6
|
hibernate.connection.password
The
database password.
|
Hibernate with MySQL Database:
MySQL is
one of the most popular open-source database systems available today. Let us
create hibernate.cfg.xml configuration file and place it in
the root of your application's classpath. You would have to make sure that you
have testdb database available in your MySQL database and you
have a user test available to access the database.
The XML
configuration file must conform to the Hibernate 3 Configuration DTD, which is
available from http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE
hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!--
Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/test
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root123
</property>
<!--
List of XML mapping files -->
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The above
configuration file includes <mapping> tags which are
related to hibernate-mapping file and we will see in next chapter what exactly
is a hibernate mapping file and how and why do we use it. Following is the list
of various important databases dialect property type:
Database
|
Dialect
Property
|
DB2
|
org.hibernate.dialect.DB2Dialect
|
HSQLDB
|
org.hibernate.dialect.HSQLDialect
|
HypersonicSQL
|
org.hibernate.dialect.HSQLDialect
|
Informix
|
org.hibernate.dialect.InformixDialect
|
Ingres
|
org.hibernate.dialect.IngresDialect
|
Interbase
|
org.hibernate.dialect.InterbaseDialect
|
Microsoft
SQL Server 2000
|
org.hibernate.dialect.SQLServerDialect
|
Microsoft
SQL Server 2005
|
org.hibernate.dialect.SQLServer2005Dialect
|
Microsoft
SQL Server 2008
|
org.hibernate.dialect.SQLServer2008Dialect
|
MySQL
|
org.hibernate.dialect.MySQLDialect
|
Oracle
(any version)
|
org.hibernate.dialect.OracleDialect
|
Oracle
11g
|
org.hibernate.dialect.Oracle10gDialect
|
Oracle
10g
|
org.hibernate.dialect.Oracle10gDialect
|
Oracle
9i
|
org.hibernate.dialect.Oracle9iDialect
|
PostgreSQL
|
org.hibernate.dialect.PostgreSQLDialect
|
Progress
|
org.hibernate.dialect.ProgressDialect
|
SAP
DB
|
org.hibernate.dialect.SAPDBDialect
|
Sybase
|
org.hibernate.dialect.SybaseDialect
|
Sybase
Anywhere
|
org.hibernate.dialect.SybaseAnywhereDialect
|
Q.15 Hibernate mapping
file?.
<?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="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee
detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
You
should save the mapping document in a file with the format
<classname>.hbm.xml. We saved our mapping document in the file
Employee.hbm.xml. Let us see little detail about the mapping elements used in
the mapping file:
·
The mapping document is an XML document having <hibernate-mapping> as
the root element which contains all the <class> elements.
·
The <class> elements are used to define
specific mappings from a Java classes to the database tables. The Java class
name is specified using the name attribute of the class element
and the database table name is specified using the table attribute.
·
The <meta> element is optional element and
can be used to create the class description.
·
The <id> element maps the unique ID
attribute in class to the primary key of the database table. The name attribute
of the id element refers to the property in the class and the column attribute
refers to the column in the database table. The type attribute
holds the hibernate mapping type, this mapping types will convert from Java to
SQL data type.
·
The <generator> element within the id
element is used to automatically generate the primary key values. Set the class attribute
of the generator element is set to native to let hibernate
pick up either identity, sequence or hilo algorithm
to create primary key depending upon the capabilities of the underlying
database.
·
The <property> element is used to map a
Java class property to a column in the database table. The name attribute
of the element refers to the property in the class and the column attribute
refers to the column in the database table. The type attribute
holds the hibernate mapping type, this mapping types will convert from Java to
SQL data type.
Q.16 What are
different types of caches available in Hibernate?
This is another common Hibernate interview question. Hibernate provides the out-of-box caching solution but there are many caches e.g. first level cache, second level cache and query cache. First level cache is maintained at Session level and cannot be disabled but the second level cache is required to be configured with external cache provider like EhCache.
Q.17. Does Hibernate Session interface is thread-safe in Java?
No, Session object is not thread-safe in Hibernate and intended to be used with-in single thread in the application.
Q.18.What is different between Session and Sessionfactory in Hibernate?
This is another common Hibernate interview question. Hibernate provides the out-of-box caching solution but there are many caches e.g. first level cache, second level cache and query cache. First level cache is maintained at Session level and cannot be disabled but the second level cache is required to be configured with external cache provider like EhCache.
Q.17. Does Hibernate Session interface is thread-safe in Java?
No, Session object is not thread-safe in Hibernate and intended to be used with-in single thread in the application.
Q.18.What is different between Session and Sessionfactory in Hibernate?
This is
another popular Hibernate interview question, mostly at a telephonic round of
interviews. The main difference between Session and SessionFactory is that
former is a single-threaded, short-lived object while later is Immutable and
shared by all Session. It also lives until the Hibernate is running. Another
difference between Session and SessionFactory is that former provides first
level cache while SessionFactory provides the Second level cache.
Q.19. What is criterion query in hibernate?
Criteria is a simplified API for retrieving entities by composing Criterion objects also known as Criterion query. This is a very convenient approach for functionality like "search" screens where you can filter data on multiple conditions as shown in the following example:
Criteria is a simplified API for retrieving entities by composing Criterion objects also known as Criterion query. This is a very convenient approach for functionality like "search" screens where you can filter data on multiple conditions as shown in the following example:
List books = session.createCriteria(Book.class)
.add(Restrictions.like("name", "dilip%") )
.add(Restrictions.like("published by
java", "2017"))
.addOrder(Order.asc("salary") )
.list();
This
can be a tough question if you are not using Hibernate on a daily basis, I have
interviewed several Java developers who have used Hibernate but doesn't know
about Criterion query or API.
Q20. What is the difference between save() and saveOrUpdate() method of Hibernate?
Though both save() and saveOrUpdate() method is used to store object into Database, the key difference between them is that save can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records.
Q.21What is
difference between getCurrentSession() and openSession() in Hibernate?
An interesting Hibernate interview question as you might have used both getCurrentSession() and openSession() to obtain an instance o
An interesting Hibernate interview question as you might have used both getCurrentSession() and openSession() to obtain an instance o
Session object.
Q.22 What is Hibernate Query Language (HQL)?
Hibernate query language, HQL is an object-oriented extension to SQL. It allows you to query, store, update, and retrieve objects from a database without using SQL. This question is also similar to the earlier question about Criterion query, Java developers who have not used Hibernate extensively will not know much about features like HQL and Criterion.
Hibernate query language, HQL is an object-oriented extension to SQL. It allows you to query, store, update, and retrieve objects from a database without using SQL. This question is also similar to the earlier question about Criterion query, Java developers who have not used Hibernate extensively will not know much about features like HQL and Criterion.
Q.23 When do you use merge() and update() in
Hibernate?
This is one of the tricky Hibernate interview questions. You should use update() if you are sure that the Hibernate session does not contain an already persistent instance with the same id and use merge() if you want to merge your modifications at any time without considering the state of the session.
This is one of the tricky Hibernate interview questions. You should use update() if you are sure that the Hibernate session does not contain an already persistent instance with the same id and use merge() if you want to merge your modifications at any time without considering the state of the session.
Q.24 How do you log SQL queries issued by the Hibernate framework in
Java application?
You can use the show_sql property to log SQL queries issued by the Hibernate framework, Just add the following line in your Hibernate configuration file:
You can use the show_sql property to log SQL queries issued by the Hibernate framework, Just add the following line in your Hibernate configuration file:
<property name=”show_sql”> true </property>
Q25. What are the three states of a Hibernate Persistence object can be?
The Hibernate persistent or entity object can live in following three states:
1) transient
2) persistent
3) detached
New objects created in Java program but not associated with any hibernate Session are said to be in the transient state. On the other hand, an object which is associated with a Hibernate session is called Persistent object. While an object which was earlier associated with Hibernate session but currently it's not associate is known as a detached object. You can call save() or persist() method to store those object into the database and bring them into the Persistent state. Similarly, you can re-attach a detached object to hibernate sessions by calling either update() or saveOrUpdate() method.
Note:-please read this all Question carefully and take job… thnks..
No comments:
Post a Comment