HB InterviewFAQ
HB InterviewFAQ
JDBC stands for Java Database Connectivity and provides a set of Java API for
accessing the relational databases from Java program. These Java APIs enables Java
programs to execute SQL statements and interact with any SQL compliant database.
What is ORM?
ORM stands for Object-Relational Mapping (ORM) is a programming technique for
converting data between relational databases and object oriented programming
languages such as Java, C# etc.
Sr.No. Advantages
Castor
TopLink
Spring DAO
Hibernate
What is Hibernate?
Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised
as an open source persistent framework created by Gavin King in 2001. It is a
powerful, high performance Object-Relational Persistence and Query service for
any Java Application.
Hibernate maps Java classes to database tables and from Java data types to
SQL data types and relieve the developer from 95% of common data persistence
related programming tasks.
Hibernate takes care of mapping Java classes to database tables using XML files
and without writing any line of code.
Provides simple APIs for storing and retrieving Java objects directly to and from
the database.
If there is change in Database or in any table then the only need to change XML
file properties.
Abstract away the unfamiliar SQL types and provide us to work around familiar
Java Objects.
DB2/NT
MySQL
PostgreSQL
FrontBase
Oracle
Name some of the java based tools/frameworks that supports hibernate integration.
Hibernate supports a variety of other technologies, including the following −
XDoclet Spring
J2EE
Eclipse plug-ins
Maven
What are the key components/objects of hibernate?
Following are the key components/objects of Hibernate −
Query − Uses SQL or Hibernate Query Language (HQL) string to retrieve data
from the database and create objects.
This component creates the connection between the Java classes and database
tables.
What is a configuration object in hibernate?
The Configuration object is the first Hibernate object you create in any Hibernate
application and usually created only once during application initialization. It represents
a configuration or properties file required by the Hibernate.
The session objects should not be kept open for a long time because they are not
usually thread safe and they should be created and destroyed them as needed.
This is an optional object and Hibernate applications may choose not to use this
interface, instead managing transactions in their own application code.
Name some of the properties you would require to configure for a databases in a
standalone situation.
Sr.No. Properties & Description
1 hibernate.dialect
This property makes Hibernate generate the appropriate SQL for the chosen
database.
2 hibernate.connection.driver_class
3 hibernate.connection.url
4 hibernate.connection.username
5 hibernate.connection.password
6 hibernate.connection.pool_size
7 hibernate.connection.autocommit
What are the three states of a persistent entity at a given point in time?
Instances may exist in one of the following three states at a given point in time −
detached − Once we close the Hibernate Session, the persistent instance will
become a detached instance.
What is the purpose of Session.beginTransaction() method?
Session.beginTransaction method begins a unit of work and returns the
associated Transaction object.
Which method is used to re-read the state of the given instance from the underlying
database?
Session.refresh re-reads the state of the given instance from the underlying database.
Which method is used to save the state of the given instance from the underlying database?
Session.save saves the state of the given instance from the underlying database.
Which method is used to update the state of the given instance from the underlying
database?
Session.update updates the state of the given instance from the underlying database.
Which method is used to save or update the state of the given instance from the underlying
database?
Java classes whose objects or instances will be stored in database tables are called persistent
classes in Hibernate.
What are the best practices that hibernate recommends for persistent classes.
There are following main rules of persistent classes, however, none of these rules are hard
requirements.
An Object/relational mappings are usually defined in an XML document. This mapping file
instructs Hibernate how to map the defined class or classes to the database tables. We should
save the mapping document in a file with the format <classname>.hbm.xml.
What is root node of hbm.xml?
The mapping document is an XML document having <hibernate-mapping> as the root element
which contains all the <class> elements.
Which element of hbm.xml defines a specific mappings from a Java classes to the database
tables?
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.
Which element of hbm.xml defines maps the unique ID attribute in class to the primary
key of the database table?
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.
Which element of hbm.xml is used to automatically generate the primary key values?
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.
Which element of hbm.xml is used to map a Java class property to a column in the
database table?
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.
This is mapped with a <set> element and initialized with java.util.TreeSet. The sort attribute can
be set to either a comparator or natural ordering.
Which element of hbm.xml is used to map a java.util.List property in hibernate?
This is mapped with a <bag> or <ibag> element and initialized with java.util.ArrayList.
This is mapped with a <map> element and initialized with java.util.TreeMap. The sort attribute
can be set to either a comparator or natural ordering.
A many-to-one association is the most common kind of association where an Object can be
associated with multiple objects. For example a same address object can be associated with
multiple employee objects.
<many-to-one> element is used to define many-to-one association. The name attribute is set to
the defined variable in the parent class. The column attribute is used to set the column name in
the parent table.
A one-to-one association is similar to many-to-one association with a difference that the column
will be set as unique. For example an address object can be associated with a single employee
object.
<many-to-one> element is used to define one-to-one association. The name attribute is set to the
defined variable in the parent class. The column attribute is used to set the column name in the
parent table which is set to unique so that only one object can be associated with an other object.
In One-to-Many mapping association, an object can be can be associated with multiple objects.
For example Employee object relates to many Certificate objects.
A One-to-Many mapping can be implemented using a Set java collection that does not contain
any duplicate element.
<one-to-many> element of set element indicates that one object relates to many other objects.
What is many-to-many association?
A Many-to-Many mapping can be implemented using a Set java collection that does not contain
any duplicate element.
<many-to-many> element indicates that one object relates to many other objects and column
attributes are used to link intermediate column.
What is the difference between save and persist methods of session object?
session.save saves the object and returns the id of the instance whereas persist do not return
anything after saving the instance.
What is the difference between get and load methods of session object?
Lazy loading is a technique in which objects are loaded on demand basis. Since Hibernate 3, lazy
loading is by default, enabled so that child objects are not loaded when parent is loaded.
What is HQL?
HQL stands for Hibernate Query Language. It takes java objects in the same way as SQL takes
tables. HQL is a Object Oriented Query language and is database independent.
What is first level cache in hibernate?
The first-level cache is the Session cache and is a mandatory cache through which all requests
must pass. The Session object keeps an object under its own power before committing it to the
database.
Second level cache is an optional cache and first-level cache will always be consulted before any
attempt is made to locate an object in the second-level cache. The second-level cache can be
configured on a per-class and per-collection basis and mainly responsible for caching objects
across sessions.
Hibernate also implements a cache for query resultsets that integrates closely with the second-
level cache.
This is an optional feature and requires two additional physical cache regions that hold the
cached query results and the timestamps when a table was last updated. This is only useful for
queries that are run frequently with the same parameters.
A concurrency strategy is a mediator which responsible for storing items of data in the cache and
retrieving them from the cache. If you are going to enable a second-level cache, you will have to
decide, for each persistent class and collection, which cache concurrency strategy to use.
Transactional − Use this strategy for read-mostly data where it is critical to prevent stale
data in concurrent transactions,in the rare case of an update.
Read-write − Again use this strategy for read-mostly data where it is critical to prevent
stale data in concurrent transactions,in the rare case of an update.
Nonstrict-read-write − This strategy makes no guarantee of consistency between the
cache and the database. Use this strategy if data hardly ever changes and a small
likelihood of stale data is not of critical concern.
Read-only − A concurrency strategy suitable for data which never changes. Use it for
reference data only.
What are Hibernate Interceptors? What are methods used it in?
An object passes through different stages in its life cycle and Interceptor Interface provides
methods, which can be called at different stages to perform some required tasks. These methods
are callbacks from the session to the application, allowing the application to inspect and/or
manipulate properties of a persistent object before it is saved, updated, deleted or loaded.
Following is the list of all the methods available within the Interceptor interface −
1
findDirty()
This method is be called when the flush() method is called on a Session object.
2
instantiate()
3
isUnsaved()
4
onDelete()
5
onFlushDirty()
This method is called when Hibernate detects that an object is dirty (i.e. have been
changed) during a flush i.e. update operation.
6
onLoad()
7
onSave()
This method is called after a flush has occurred and an object has been updated in memory.
9
preFlush()
Hibernate Interceptor gives us total control over how an object will look to both the application
and the database.
How can we use new custom interfaces to enhance functionality of built-in interfaces of
hibernate?
We can use extension interfaces in order to add any required functionality which isn’t supported
by built-in interfaces.
Should all the mapping files of hibernate have .hbm.xml extension to work properly?
No, having .hbm.xml extension is a convention and not a requirement for hibernate mapping file
names. We can have any extension for these mapping files.
POJOs( Plain Old Java Objects) are java beans with proper getter and setter methods for each
and every properties.
Use of POJOs instead of simple java classes results in an efficient and well constructed code.
What is Java Persistence API (JPA)?
Java Persistence API (JPA) provides specification for managing the relational data in
applications. Current JPA version 2.1 was started in July 2011 as JSR 338. JPA 2.1 was
approved as final on 22 May 2013.
1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of
managing resources, so we can focus on business logic.
2. Hibernate framework provides support for XML as well as JPA annotations, that makes
our code implementation independent.
3. Hibernate provides a powerful query language (HQL) that is similar to SQL. However,
HQL is fully object-oriented and understands concepts like inheritance, polymorphism and
association.
4. Hibernate is an open source project from Red Hat Community and used worldwide. This
makes it a better choice than others because learning curve is small and there are tons of
online documentations and help is easily available in forums.
5. Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring
Framework provides built-in support for integrating hibernate with Spring applications.
6. Hibernate supports lazy initialization using proxy objects and perform actual database
queries only when it’s required.
7. Hibernate cache helps us in getting better performance.
8. For database vendor specific feature, hibernate is suitable because we can also execute
native sql queries.
Overall hibernate is the best choice in current market for ORM tool, it contains all the features
that you will ever need in an ORM tool.
1. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks
more cleaner and readable.
2. Hibernate supports inheritance, associations and collections. These features are not present
with JDBC API.
3. Hibernate implicitly provides transaction management, in fact most of the queries can’t be
executed outside transaction. In JDBC API, we need to write code for transaction
management using commit and rollback. Read more at JDBC Transaction Management.
4. JDBC API throws SQLException that is a checked exception, so we need to write a lot of
try-catch block code. Most of the times it’s redundant in every JDBC call and used for
transaction management. Hibernate wraps JDBC exceptions and
throw JDBCException or HibernateException un-checked exception, so we don’t need to
write code to handle it. Hibernate built-in transaction management removes the usage of
try-catch blocks.
5. Hibernate Query Language (HQL) is more object oriented and close to java programming
language. For JDBC, we need to write native sql queries.
6. Hibernate supports caching that is better for performance, JDBC queries are not cached
hence performance is low.
7. Hibernate provide option through which we can create database tables too, for JDBC
tables must exist in the database.
8. Hibernate configuration helps us in using JDBC like connection as well as JNDI
DataSource for connection pool. This is very important feature in enterprise application
and completely missing in JDBC API.
9. Hibernate supports JPA annotations, so code is independent of implementation and easily
replaceable with other ORM tools. JDBC code is very tightly coupled with the application.
1. javax.persistence.Entity: Used with model classes to specify that they are entity beans.
2. javax.persistence.Table: Used with entity beans to define the corresponding table name
in database.
3. javax.persistence.Access: Used to define the access type, either field or property. Default
value is field and if you want hibernate to use getter/setter methods then you need to set it
to property.
4. javax.persistence.Id: Used to define the primary key in the entity bean.
5. javax.persistence.EmbeddedId: Used to define composite primary key in the entity bean.
6. javax.persistence.Column: Used to define the column name in database table.
7. javax.persistence.GeneratedValue: Used to define the strategy to be used for generation
of primary key. Used in conjunction with javax.persistence.GenerationType enum.
8. javax.persistence.OneToOne: Used to define the one-to-one mapping between two entity
beans. We have other similar annotations as OneToMany, ManyToOne and ManyToMany
9. org.hibernate.annotations.Cascade: Used to define the cascading between two entity
beans, used with mappings. It works in conjunction
with org.hibernate.annotations.CascadeType
10. javax.persistence.PrimaryKeyJoinColumn: Used to define the property for foreign key.
Used
with org.hibernate.annotations.GenericGenerator and org.hibernate.annotations.Parameter
There are five collection types in hibernate used for one-to-many relationship mappings.
We can set below property for hibernate configuration to log SQL queries.
<property name="hibernate.show_sql">true</property>
Hibernate use proxy classes for lazy loading of data, only when it’s needed. This is done by
extending the entity bean, if the entity bean will be final then lazy loading will not be possible,
hence low performance.
When we have relationship between entities, then we need to define how the different operations
will affect the other entity. This is done by cascading and there are different types of it.
Here is a simple example of applying cascading between primary and secondary entities.
import org.hibernate.annotations.Cascade;
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@OneToOne(mappedBy = "employee")
@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Address address;
}
Note that Hibernate CascadeType enum constants are little bit different from
JPA javax.persistence.CascadeType, so we need to use the Hibernate CascadeType and Cascade
annotations for mappings, as shown in above example.
Commonly used cascading types as defined in CascadeType enum are:
1. None: No Cascading, it’s not a type but when we don’t define any cascading then no
operations in parent affects the child.
2. ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist. Basically
everything
3. SAVE_UPDATE: Cascades save and update, available only in hibernate.
4. DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
5. DETATCH, MERGE, PERSIST, REFRESH and REMOVE – for similar operations
6. LOCK: Corresponds to the Hibernate native LOCK action.
7. REPLICATE: Corresponds to the Hibernate native REPLICATE action.
Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM
framework. That’s why Spring Hibernate combination is used a lot in enterprise applications.
The best part with using Spring is that it provides out-of-box integration support for Hibernate
with Spring ORM module. Following steps are required to integrate Spring and Hibernate
frameworks together.
When Spring and Hibernate integration started, Spring ORM provided two helper classes –
HibernateDaoSupport and HibernateTemplate. The reason to use them was to get the Session
from Hibernate and get the benefit of Spring transaction management. However from Hibernate
3.0.1, we can use SessionFactory getCurrentSession() method to get the current session and use
it to get the spring transaction management benefits. If you go through above examples, you will
see how easy it is and that’s why we should not use these classes anymore.
One other benefit of HibernateTemplate was exception translation but that can be achieved easily
by using @Repository annotation with service classes, shown in above spring mvc example. This
is a trick question to judge your knowledge and whether you are aware of recent developments or
not.
Domain Model Pattern – An object model of the domain that incorporates both behavior
and data.
Data Mapper – A layer of Mappers that moves data between objects and a database while
keeping them independent of each other and the mapper itself.
Proxy Pattern for lazy loading
Factory pattern in SessionFactory
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.
The <generator> subelement of id used to generate the unique identifier for the objects of
persistent class. There are many generator classes defined in the Hibernate Framework.
1. assigned
2. increment
3. sequence
4. hilo
5. native
6. identity
7. seqhilo
8. uuid
9. guid
10. select
11. foreign
12. sequence-identity
1) assigned
It is the default generator strategy if there is no <generator> element . In this case, application
assigns the id. For example:
1. ...
2. <hibernate-mapping>
3. <class ...>
4. <id ...>
5. <generator class="assigned"></generator>
6. </id>
7.
8. .....
9.
10. </class>
11. </hibernate-mapping>
2) increment
It generates the unique id only if no other process is inserting data into this table. It
generates short, int or long type identifier. The first generated identifier is 1 normally and
incremented as 1. Syntax:
1. ....
2. <hibernate-mapping>
3. <class ...>
4. <id ...>
5. <generator class="increment"></generator>
6. </id>
7.
8. .....
9.
10. </class>
11. </hibernate-mapping>
3) sequence
It uses the sequence of the database. if there is no sequence defined, it creates a sequence
automatically e.g. in case of Oracle database, it creates a sequence named
HIBERNATE_SEQUENCE. In case of Oracle, DB2, SAP DB, Postgre SQL or McKoi, it uses
sequence but it uses generator in interbase. Syntax:
1. .....
2. <id ...>
3. <generator class="sequence"></generator>
4. </id>
5. .....
For defining your own sequence, use the param subelement of generator.
1. .....
2. <id ...>
3. <generator class="sequence">
4. <param name="sequence">your_sequence_name</param>
5. </generator>
6. </id>
7. .....
4) hilo
It uses high and low algorithm to generate the id of type short, int and long. Syntax:
1. .....
2. <id ...>
3. <generator class="hilo"></generator>
4. </id>
5. ....
5) native
It uses identity, sequence or hilo depending on the database vendor. Syntax:
1. .....
2. <id ...>
3. <generator class="native"></generator>
4. </id>
5. .....
6) identity
It is used in Sybase, My SQL, MS SQL Server, DB2 and HypersonicSQL to support the id
column. The returned id is of type short, int or long.
7) seqhilo
It uses high and low algorithm on the specified sequence name. The returned id is of type short,
int or long.
8) uuid
It uses 128-bit UUID algorithm to generate the id. The returned id is of type String, unique
within a network (because IP is used). The UUID is represented in hexadecimal digits, 32 in
length.
9) guid
It uses GUID generated by database of type string. It works on MS SQL Server and MySQL.
10) select
11) foreign
It uses the id of another associated object, mostly used with <one-to-one> association.
12) sequence-identity
It uses a special sequence generation strategy. It is supported in Oracle 10g drivers only.