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

HB InterviewFAQ

JDBC provides Java APIs for accessing relational databases. ORM converts data between databases and object-oriented languages. Hibernate is a popular ORM framework that maps Java classes to database tables and handles common data tasks.

Uploaded by

subhabirajdar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

HB InterviewFAQ

JDBC provides Java APIs for accessing relational databases. ORM converts data between databases and object-oriented languages. Hibernate is a popular ORM framework that maps Java classes to database tables and handles common data tasks.

Uploaded by

subhabirajdar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

What is JDBC?

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.

What are the advantages of ORM over JDBC?


An ORM system has following advantages over plain JDBC

Sr.No. Advantages

1 Lets business code access objects rather than DB tables.

2 Hides details of SQL queries from OO logic.

3 Based on JDBC 'under the hood'

4 No need to deal with the database implementation.

5 Entities based on business concepts rather than database structure.

6 Transaction management and automatic key generation.

7 Fast development of application.


Name some of the ORM frameworks based on JAVA.
There are several persistent frameworks and ORM options in Java.

 Enterprise JavaBeans Entity Beans

 Java Data Objects

 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.

What are the advantages of using Hibernate?


Following are the advantages of using Hibernate.

 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.

 Hibernate does not require an application server to operate.

 Manipulates Complex associations of objects of your database.

 Minimize database access with smart fetching strategies.


 Provides Simple querying of data.

Name some of the databases that hibernate supports.


Hibernate supports almost all the major RDBMS. Following is list of few of the database
engines supported by Hibernate.

 HSQL Database Engine

 DB2/NT

 MySQL

 PostgreSQL

 FrontBase

 Oracle

 Microsoft SQL Server Database

 Sybase SQL Server

 Informix Dynamic Server

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 −

 Configuration − Represents a configuration or properties file required by the


Hibernate.

 SessionFactory − Configures Hibernate for the application using the supplied


configuration file and allows for a Session object to be instantiated.

 Session − Used to get a physical connection with a database.


 Transaction − Represents a unit of work with the database and most of the
RDBMS supports transaction functionality.

 Query − Uses SQL or Hibernate Query Language (HQL) string to retrieve data
from the database and create objects.

 Criteria − Used to create and execute object oriented criteria queries to


retrieve objects.
What are the two key components of a hibernate configuration object?
The Configuration object provides two keys components −

 Database Connection − This is handled through one or more configuration


files supported by Hibernate. These files
are hibernate.properties and hibernate.cfg.xml.

 Class Mapping Setup

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.

What is a SessionFactory in hibernate?


Configuration object is used to create a SessionFactory object which inturn configures
Hibernate for the application using the supplied configuration file and allows for a
Session object to be instantiated. The SessionFactory is a thread safe object and used
by all the threads of an application.

The SessionFactory is heavyweight object so usually it is created during application


start up and kept for later use. You would need one SessionFactory object per
database using a separate configuration file. So if you are using multiple databases
then you would have to create multiple SessionFactory objects.
What is Session in hibernate?
A Session is used to get a physical connection with a database. The Session object is
lightweight and designed to be instantiated each time an interaction is needed with the
database. Persistent objects are saved and retrieved through a Session object.

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.

What is Transaction in hibernate?


A Transaction represents a unit of work with the database and most of the RDBMS
supports transaction functionality. Transactions in Hibernate are handled by an
underlying transaction manager and transaction (from JDBC or JTA).

This is an optional object and Hibernate applications may choose not to use this
interface, instead managing transactions in their own application code.

What is Query in hibernate?


Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data
from the database and create objects. A Query instance is used to bind query
parameters, limit the number of results returned by the query, and finally to execute
the query.

What is Criteria in hibernate?


Criteria object are used to create and execute object oriented criteria queries to
retrieve objects.

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

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.

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 −

 transient − A new instance of a a persistent class which is not associated with


a Session and has no representation in the database and no identifier value is
considered transient by Hibernate.

 persistent − You can make a transient instance persistent by associating it with


a Session. A persistent instance has a representation in the database, an
identifier value and is associated with a Session.

 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 add a criteria to a query?


Session.createCriteria creates a new Criteria instance, for the given entity class, or a
superclass of an entity class.

Which method is used to create a HQL query?


Session.createQuery creates a new instance of Query for the given HQL query string.

Which method is used to create a SQL query?


Session.createSQLQuery creates a new instance of SQLQuery for the given SQL query
string.

Which method is used to remove a persistent instance from the datastore?


Session.delete removes a persistent instance from the datastore.

Which method is used to get a persistent instance from the datastore?


Session.get returns the persistent instance of the given named entity with the given
identifier, or null if there is no such persistent instance.

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?

Session.saveOrUpdate either savesObjectObject or updatesObjectObject the given instance.

What are persistent classes in hibernate?

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.

 All Java classes that will be persisted need a default constructor.


 All classes should contain an ID in order to allow easy identification of your objects
within Hibernate and the database. This property maps to the primary key column of a
database table.
 All attributes that will be persisted should be declared private and
have getXXX and setXXXmethods defined in the JavaBean style.
 A central feature of Hibernate, proxies, depends upon the persistent class being either
non-final, or the implementation of an interface that declares all public methods.
 All classes that do not extend or implement some specialized classes and interfaces
required by the EJB framework.

Where Object/relational mappings are defined in hibernate?

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.

Which element of hbm.xml is used to map a java.util.Set property in hibernate?

This is mapped with a <set> element and initialized with java.util.HashSet.

Which element of hbm.xml is used to map a java.util.SortedSet property in hibernate?

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 <list> element and initialized with java.util.ArrayList.

Which element of hbm.xml is used to map a java.util.Collection property in hibernate?

This is mapped with a <bag> or <ibag> element and initialized with java.util.ArrayList.

Which element of hbm.xml is used to map a java.util.Map property in hibernate?

This is mapped with a <map> element and initialized with java.util.HashMap.

Which element of hbm.xml is used to map a java.util.SortedMap property in hibernate?

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.

What is many-to-one association?

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.

What is one-to-one association?

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.

What is one-to-many association?

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.

Is SessionFactory a thread-safe object?

Yes, SessionFactory is a thread-safe and can be accessed by multiple threads simultaneously.

Is Session a thread-safe object?

No, Session is not thread-safe.

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?

There are following differences between get and load methods.

 get returns null if no data is present where as load throws ObjectNotFoundException


exception in such case.
 get always hits the database whereas load method doesn't hit the database.
 get returns actual object whereas load returns proxy object.
 A central feature of Hibernate, proxies, depends upon the persistent class being either
non-final, or the implementation of an interface that declares all public methods.
 All classes that do not extend or implement some specialized classes and interfaces
required by the EJB framework.

What is lazy loading?

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.

What is second level cache in hibernate?

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.

What is Query level cache in hibernate?

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.

What are concurrency strategies?

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 −

Sr.No. Method & Description

1
findDirty()

This method is be called when the flush() method is called on a Session object.

2
instantiate()

This method is called when a persisted class is instantiated.

3
isUnsaved()

This method is called when an object is passed to the saveOrUpdate() method/

4
onDelete()

This method is called before an object is deleted.

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()

This method is called before an object is initialized.

7
onSave()

This method is called before an object is saved.


8
postFlush()

This method is called after a flush has occurred and an object has been updated in memory.

9
preFlush()

This method is called before a flush.

Hibernate Interceptor gives us total control over how an object will look to both the application
and the database.

What’s the usage of Configuration Interface in hibernate?


Configuration interface of hibernate framework is used to configure hibernate. It’s also used to
bootstrap hibernate. Mapping documents of hibernate are located using this interface.

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.

How do we create session factory in hibernate?


To create a session factory in hibernate, an object of configuration is created first which refers
to the path of configuration file and then for that configuration, session factory is created as
given in the example below:
Configuration config = new Configuration();
config.addResource(&amp;amp;quot;myinstance/configuration.hbm.xml&amp;amp;quot;);
config.setProperties( System.getProperties() );
SessionFactory sessions = config.buildSessionFactory();

What are POJOs and what’s their significance?

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.

JPA specifications is defined with annotations in javax.persistence package. Using JPA


annotation helps us in writing implementation independent code.

What are the important benefits of using Hibernate Framework?

Some of the important benefits of using hibernate framework are:

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.

What are the advantages of Hibernate over JDBC?

Some of the important advantages of Hibernate framework over JDBC are:

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.

Name some important annotations used for Hibernate mapping?

Hibernate supports JPA annotations and it has some other annotations


in org.hibernate.annotations package. Some of the important JPA and hibernate annotations used
are:

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

What will happen if we don’t have no-args constructor in Entity bean?


Hibernate uses Reflection API to create instance of Entity beans, usually when you call get() or
load() methods. The method Class.newInstance() is used for this and it requires no-args
constructor. So if you won’t have no-args constructor in entity beans, hibernate will fail to
instantiate it and you will get HibernateException.

What are the collection types in Hibernate?

There are five collection types in hibernate used for one-to-many relationship mappings.

1. Bag & IdBag


2. Set
3. List
4. Array
5. Map

How to implement Joins in Hibernate?

There are various ways to implement joins in hibernate.

 Using associations such as one-to-one, one-to-many etc.


 Using JOIN in the HQL query. There is another form “join fetch” to load associated data
simultaneously, no lazy loading.
 We can fire native sql query and use join keyword.

How to log hibernate generated sql queries in log files?

We can set below property for hibernate configuration to log SQL queries.

<property name="hibernate.show_sql">true</property>

Why we should not make Entity Class final?

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.

What is cascading and what are different types of cascading?

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.

How to integrate Hibernate and Spring frameworks?

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.

1. Add hibernate-entitymanager, hibernate-core and spring-orm dependencies.


2. Create Model classes and corresponding DAO implementations for database operations.
Note that DAO classes will use SessionFactory that will be injected by Spring Bean
configuration.
3. If you are using Hibernate 3, you need to
configure org.springframework.orm.hibernate3.LocalSessionFactoryBean or org.springfra
mework.orm.hibernate3.annotation.AnnotationSessionFactoryBean in Spring Bean
configuration file. For Hibernate 4, there is single
class org.springframework.orm.hibernate4.LocalSessionFactoryBean that should be
configured.
4. Note that we don’t need to use Hibernate Transaction Management, we can leave it to
Spring declarative transaction management using @Transactional annotation.

What is HibernateTemplate class?

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.

Which design patterns are used in Hibernate framework?

Some of the design patterns used in Hibernate Framework are:

 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

What does Session lock() method do in Hibernate?


This one is one of the tricky Hibernate Interview questions because Session's lock() method
reattach object without synchronizing or updating with the 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 the database during reattachment. Sometimes this Hibernate question is also asked
as what is difference between Session's lock() and update() method.
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.

What is a SessionFactory in hibernate?


Configuration object is used to create a SessionFactory object which inturn configures Hibernate
for the application using the supplied configuration file and allows for a Session object to be
instantiated. The SessionFactory is a thread safe object and used by all the threads of an
application.
The SessionFactory is heavyweight object so usually it is created during application start up and
kept for later use. You would need one SessionFactory object per database using a separate
configuration file. So if you are using multiple databases then you would have to create multiple
SessionFactory objects.

What is Session in hibernate?


A Session is used to get a physical connection with a database. The Session object is lightweight
and designed to be instantiated each time an interaction is needed with the database. Persistent
objects are saved and retrieved through a Session object.
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.

What is Transaction in hibernate?


A Transaction represents a unit of work with the database and most of the RDBMS supports
transaction functionality. Transactions in Hibernate are handled by an underlying transaction
manager and transaction fromJDBCorJTA.
This is an optional object and Hibernate applications may choose not to use this interface, instead
managing transactions in their own application code.

What is Query in hibernate?


Query objects use SQL or Hibernate Query Language HQL string to retrieve data from the
database
and create objects. A Query instance is used to bind query parameters, limit the number of results
returned by the query, and finally to execute the query.
What is Criteria in hibernate?
Criteria object are used to create and execute object oriented criteria queries to retrieve objects.
Name some of the properties you would require to configure for a databases in a standalone
situation.

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.

What are generators classes in Hibernate?

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.

All the generator classes implements the org.hibernate.id.IdentifierGenerator interface. The


application programmer may create one's own generator classes by implementing the
IdentifierGenerator interface. Hibernate framework provides many built-in generator classes:

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

It uses the primary key returned by the database trigger.

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy