Here we have mentioned most frequently asked Hibernate Interview Questions and Answers specially for freshers and experienced.


 

1. What’s Hibernate?

Ans:

Hibernate is a popular framework of Java which allows an efficient Object Relational mapping using configuration files in XML format. After java objects mapping to database tables, database is used and handled using Java objects without writing complex database queries.

2. What is ORM?

Ans:

ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework which maps database tables with Java Objects and then provides various API’s to perform different types of operations on the data tables.

3. How properties of a class are mapped to the columns of a database table in Hibernate?

Ans:

Mappings between class properties and table columns are specified in XML file.

4. What’s the usage of Configuration Interface in hibernate?

Ans:

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.

5. How can we use new custom interfaces to enhance functionality of built-in interfaces of hibernate?

Ans:

We can use extension interfaces in order to add any required functionality which isn’t supported by built-in interfaces.

6. Should all the mapping files of hibernate have .hbm.xml extension to work properly?

Ans:

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.

7. How do we create session factory in hibernate?

Ans:

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:
Java

Configuration config = new Configuration();
config.addResource("myinstance/configuration.hbm.xml");
config.setProperties( System.getProperties() );
SessionFactory sessions = config.buildSessionFactory();

8. What are POJOs and what’s their significance?

Ans:

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.

9. What’s HQL?

Ans:

HQL is the query language used in Hibernate which is an extension of SQL. HQL is very efficient, simple and flexible query language to do various type of operations on relational database without writing complex database queries.

10. What is Query level cache in hibernate?

Ans:

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.



 

11. What is criteria API?

Ans:

Criteria is a simple yet powerful API of hibernate which is used to retrieve entities through criteria object composition.

12. What are the benefits of using Hibernate template?

Ans:

Following are some key benefits of using Hibernate template:
a. Session closing is automated.
b. Interaction with hibernate session is simplified.
c. Exception handling is automated.

13. What are concurrency strategies?

Ans:

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.

14. What are the two types of collections in hibernate?

Ans:

Following are the two types of collections in hibernate:
a. Sorted Collection
b. Order Collection

15. What’s the difference between session.save() and session.saveOrUpdate() methods in hibernate?

Ans:

Sessionsave() method saves a record only if it’s unique with respect to its primary key and will fail to insert if primary key already exists in the table.
saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.

16. What the benefits are of hibernate over JDBC?

Ans:

a. Hibernate can be used seamlessly with any type of database as its database independent while in case of JDBC, developer has to write database specific queries.
b. Using hibernate, developer doesn’t need to be an expert of writing complex queries as HQL simplifies query writing process while in case of JDBC, its job of developer to write and tune queries.
c. In case of hibernate, there is no need to create connection pools as hibernate does all connection handling automatically while in case of JDBC, connection pools need to be created.

17. How can we get hibernate statistics?

Ans:

We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below:
SessionFactory.getStatistics()

18. What is transient instance state in Hibernate?

Ans:

If an instance is not associated with any persistent context and also, it has never been associated with any persistent context, then it’s said to be in transient state.

19. How can we reduce database write action times in Hibernate?

Ans:

Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.

20. What’s the usage of callback interfaces in hibernate?

Ans:

Callback interfaces of hibernate are useful in receiving event notifications from objects. For example, when an object is loaded or deleted, an event is generated and notification is sent using callback interfaces.




 

21. When an instance goes in detached state in hibernate?

Ans:

When an instance was earlier associated with some persistent context (e.g. a table) and is no longer associated, it’s called to be in detached state.

22. What the four ORM levels are in hibernate?

Ans:

Following are the four ORM levels in hibernate:
a. Pure Relational
b. Light Object Mapping
c. Medium Object Mapping
d. Full Object Mapping

23. What’s transaction management in hibernate? How it works?

Ans:

Transaction management is the process of managing a set of statements or commands. In hibernate; transaction management is done by transaction interface as shown in below code:
Java

Session s = null;
Transaction tr = null;
try {
s = sessionFactory.openSession();
tr = s.beginTransaction();
doTheAction(s);
tr.commit();
} catch (RuntimeException exc) {
tr.rollback();
} finally {
s.close();
}

24. What the two methods are of hibernate configuration?

Ans:

We can use any of the following two methods of hibernate configuration:
a. XML based configuration ( using hibernate.cfg.xml file)
b. Programmatic configuration ( Using code logic)

25. What is the default cache service of hibernate?

Ans:

Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and TreeCache and default cache service of hibernate is EHCache.

26. What are the two mapping associations used in hibernate?

Ans:

In hibernate; we have following two types of mapping associations between entities:
a. One-to-One Association
b. Many-to-Many Association

27. What’s the usage of Hibernate QBC API?

Ans:

Hibernate Query By Criteria (QBC) API is used to create queries by manipulation of criteria objects at runtime.

28. In how many ways, objects can be fetched from database in hibernate?

Ans:

Hibernate provides following four ways to fetch objects from database:
a. Using HQL
b. Using identifier
c. Using Criteria API
d. Using Standard SQL

29. What is second level cache in hibernate?

Ans:

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.

30. How can we reattach any detached objects in Hibernate?

Ans:

Objects which have been detached and are no longer associated with any persistent entities can be reattached by calling session.merge() method of session class.


 

31. What are different ways to disable hibernate second level cache?

Ans:

Hibernate second level cache can be disabled using any of the following ways:
a. By setting use_second_level_cache as false.
b. By using CACHEMODE.IGNORE
c. Using cache provider as org.hibernate.cache.NoCacheProvider

32. What is ORM metadata?

Ans:

All the mapping between classes and tables, properties and columns, Java types and SQL types etc is defined in ORM metadata.

33. Which one is the default transaction factory in hibernate?

Ans:

With hibernate 3.2, default transaction factory is JDBCTransactionFactory.

34. What’s the role of JMX in hibernate?

Ans:

Java Applications and components are managed in hibernate by a standard API called JMX API. JMX provides tools for development of efficient and robust distributed, web based solutions.

35. How can we bind hibernate session factory to JNDI ?

Ans:

Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file.

36. In how many ways objects can be identified in Hibernate?

Ans:

Object identification can be done in hibernate in following three ways:
a. Using Object Identity: Using == operator.
b. Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent same row.

37. What different fetching strategies are of hibernate?

Ans:

Following fetching strategies are available in hibernate:
1. Join Fetching
2. Batch Fetching
3. Select Fetching
4. Sub-select Fetching

38. What is first level cache in hibernate?

Ans:

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.

39. What are derived properties in hibernate?

Ans:

Derived properties are those properties which are not mapped to any columns of a database table. Such properties are calculated at runtime by evaluation of any expressions.

40. What is meant by a Named SQL Query in hibernate and how it’s used?

Ans:

Named SQL queries are those queries which are defined in mapping file and are called as required anywhere.
For example, we can write a SQL query in our XML mapping file as follows:
Then this query can be called as follows:
Java

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


 

41. What’s the difference between load() and get() method in hibernate?

Ans:

Load() methods results in an exception if the required records isn’t found in the database while get() method returns null when records against the id isn’t found in the database.
So, ideally we should use Load() method only when we are sure about existence of records against an id.

42. What’s the use of version property in hibernate?

Ans:

Version property is used in hibernate to know whether an object is in transient state or in detached state.

43. What is attribute oriented programming?

Ans:

In Attribute oriented programming, a developer can add Meta data (attributes) in the java source code to add more significance in the code. For Java (hibernate), attribute oriented programming is enabled by an engine called XDoclet.

44. What’s the use of session.lock() in hibernate?

Ans:

session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.

45. Does hibernate support polymorphism?

Ans:

Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism associations are supported in all mapping strategies of hibernate.

46. What the three inheritance models are of hibernate?

Ans:

Hibernate has following three inheritance models:
a. Tables Per Concrete Class
b. Table per class hierarchy
c. Table per sub-class

47. How can we map the classes as immutable?

Ans:

If we don’t want an application to update or delete objects of a class in hibernate, we can make the class as immutable by setting mutable=false

48. What’s general hibernate flow using RDBMS?

Ans:

General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.

49. What is Light Object Mapping?

Ans:

Light Object Mapping is one of the levels of ORM quality in which all entities are represented as classes and they are mapped manually.

50. What’s difference between managed associations and hibernate associations?

Ans:

Managed associations relate to container management persistence and are bi-directional while hibernate associations are unidirectional.




 

51. What is Hibernate?

Ans:

Hibernate is a powerful, high performance object/relational persistence and query service.
This lets the users to develop persistent classes following object-oriented principles such as association, inheritance, polymorphism, composition, and collections.

52. What is ORM?

Ans:

ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

53. What does an ORM solution comprises of?

Ans:

• It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes
• 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 dirty checking, lazy association fetching, and other optimization functions

54. What are the different levels of ORM quality?

Ans:

There are four levels defined for ORM quality.
i. Pure relational
ii. Light object mapping
iii. Medium object mapping
iv. Full object mapping

55. What is a pure relational ORM?

Ans:

The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

56. What is a meant by light object mapping?

Ans:

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. This approach is most known to all.

57. What is a meant by medium object mapping?

Ans:

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. Used when the mapping exceeds 25 different database products at a time.

58. What is meant by full object mapping?

Ans:

Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism 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.

59. 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.
i. Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.
ii. 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.
iii. 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.
iv. Vendor independence – Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

60. How does hibernate code looks like?

Ans:

Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass (“Sample App”);
session.save(mpc);
tx.commit();
session.close();

The Session and Transaction are the interfaces provided by hibernate. There are many other interfaces besides this.


 

61. What is a hibernate xml mapping document and how does it look like?

Ans:

In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes’ map to the columns of the relative tables in database.

62. What the Core interfaces are of hibernate framework?

Ans:

There are many benefits from these. Out of which the following are the most important one.
i. Session Interface – This is the primary interface used by hibernate applications.
The instances of this interface are lightweight and are inexpensive to create and destroy.Hibernate sessions are not thread safe.
ii. SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.
iii. Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
iv. Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
v. Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.

63. What are Callback interfaces?

Ans:

These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.

64. What are Extension interfaces?

Ans:

When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.

65. What are the Extension interfaces that are there in hibernate?

Ans:

There are many extension interfaces provided by hibernate.
ProxyFactory interface – used to create proxies
ConnectionProvider interface – used for JDBC connection management
TransactionFactory interface – Used for transaction management
Transaction interface – Used for transaction management
TransactionManagementLookup interface – Used in transaction management.
Cahce interface – provides caching techniques and strategies
CacheProvider interface – same as Cache interface
ClassPersister interface – provides ORM strategies
IdentifierGenerator interface – used for primary key generation
Dialect abstract class – provides SQL support

66. What are different environments to configure hibernate?

Ans:

There are mainly two types of environments in which the configuration of hibernate application differs.
i. Managed environment – In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere.
ii. Non-managed environment – This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.

67. What is the file extension you use for hibernate mapping file?

Ans:

The name of the file should be like this : filename.hbm.xml.The filename varies here. The extension of these files should be “.hbm.xml”.This is just a convention and it’s not mandatory. But this is the best practice to follow this extension.

68. What do you create a SessionFactory?

Ans:

Configuration cfg = new Configuration();
cfg.addResource(“myinstance/MyConfig.hbm.xml”);
cfg.setProperties( System.getProperties() );
SessionFactory sessions = cfg.buildSessionFactory();

First, we need to create an instance of Configuration and use that instance to refer to the location of the configuration file. After configuring this instance is used to create the SessionFactory by calling the method buildSessionFactory().

69. What is meant by Method chaining?

Ans:

Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. And it is not mandatory to use this format. Look how a SessionFactory is created when we use method chaining.

SessionFactory sessions = new Configuration()
sessions.addResource(“myinstance/MyConfig.hbm.xml”)
sessions.setProperties( System.getProperties() ).buildSessionFactory();

70. What does hibernate.properties file consist of?

Ans:

This is a property file that should be placed in application class path. So when the
Configuration object is created, hibernate is first initialized. At this moment the
application will automatically detect and read this hibernate.properties file.
hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB
hibernate.transaction.factory_class =
net.sf.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class =
net.sf.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect



 

71. What should SessionFactory be placed so that it can be easily accessed?

Ans:

As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file.

72. What are POJOs?

Ans:

POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather then simple java classes.

73. What is object/relational mapping metadata?

Ans:

ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations.

74. What is HQL?

Ans:

HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.

75. What are the different types of property and class mappings?

Ans:

• Typical and most common property mapping

• Derived properties

• Typical and most common property mapping

• Controlling inserts and updates

 

76. What is Attribute Oriented Programming?

Ans:

XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses the Javadoc tag format (@attribute) to specify class-, field-, or method-level metadata attributes. These attributes are used to generate hibernate mapping file automatically when the application is built. This kind of programming that works on attributes is called as Attribute Oriented Programming.

77. What are the different methods of identifying an object?

Ans:

There are three methods by which an object can be identified.
i. Object identity –Objects are identical if they reside in the same memory location in the JVM. This can be checked by using the = = operator.
ii. Object equality – Objects are equal if they have the same value, as defined by the equals( ) method. Classes that don’t explicitly override this method inherit the implementation defined by java.lang.Object, which compares object identity.
iii. Database identity – Objects stored in a relational database are identical if they represent the same row or, equivalently, share the same table and primary key value.

78. What are the different approaches to represent an inheritance hierarchy?

Ans:

i. Table per concrete class.
ii. Table per class hierarchy.
iii. Table per subclass.

79. What are managed associations and hibernate associations?

Ans:

Associations that are related to container management persistence are called managed associations. These are bi-directional associations. Coming to hibernate associations,these are unidirectional.

80. What is the Session factory interface ?

Ans:

It creates new hibernate sessions by referencing immutable and thread safe objects. Application using hibernate are usually allowed and desgined to implement single instance of the class using this interface. Only single instance of a class can be used which is using this interface.




 

81. What is the session interface?

Ans:

This represents hibernate session which perform the manipulation on the database entities. Some of the activities performed by session interface are as follows they are managing the persistence state, fetching persisted ones and management of the transaction demarcation.

82. What is the Steps involved in creating database applications with Java using Hibernate ?

Ans:

Creating Database applications with Java is made simpler with Hibernate. First Plain old java object needs to be written, XML mapping file should be created which shows relationship between database and class attributes. Hibernate APIs can be used to store persistent objects.

83. What is JDBC?

Ans:

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.

84. What is ORM?

Ans:

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.

85. What are the advantages of ORM over JDBC?

Ans:

An ORM system has following advantages over plain JDBC

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

86. Name some of the ORM frameworks based on JAVA.

Ans:

There are several persistent frameworks and ORM options in Java.
Enterprise JavaBeans Entity Beans
Java Data Objects
Castor
TopLink
Spring DAO
Hibernate

87. What is Hibernate?

Ans:

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.

88. What are the advantages of using Hibernate?

Ans:

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.

89. Name some of the databases that hibernate supports.

Ans:

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

90. Name some of the java based tools/frameworks that supports hibernate integration.

Ans:

Hibernate supports a variety of other technologies, including the following –
XDoclet Spring
J2EE
Eclipse plug-ins
Maven


 

91. What are the key components/objects of hibernate?

Ans:

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.

92. What are the two key components of a hibernate configuration object?

Ans:

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.

93. What is a configuration object in hibernate?

Ans:

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.

94. What is a SessionFactory in hibernate?

Ans:

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.

95. What is Session in hibernate?

Ans:

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.

96. What is Transaction in hibernate?

Ans:

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.

97. What is Query in hibernate?

Ans:

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.

98. What is Criteria in hibernate?

Ans:

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

99. Name some of the properties you would require to configure for a databases in a standalone situation.

Ans:

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

100. What are the three states of a persistent entity at a given point in time?

Ans:

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.



 

101. What is the purpose of Session.beginTransaction() method?

Ans:

Session.beginTransaction method begins a unit of work and returns the associated Transaction object.

102. Which method is used to add a criteria to a query?

Ans:

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

103. Which method is used to create a HQL query?

Ans:

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

104. Which method is used to create a SQL query?

Ans:

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

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

Ans:

Session.delete removes a persistent instance from the datastore.

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

Ans:

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

107. Which method is used to re-read the state of the given instance from the underlying database?

Ans:

Session.refresh re-reads the state of the given instance from the underlying database.

108. Which method is used to save the state of the given instance from the underlying database?

Ans:

Session.save saves the state of the given instance from the underlying database.

109. Which method is used to update the state of the given instance from the underlying database?

Ans:

Session.update updates the state of the given instance from the underlying database.

110. Which method is used to save or update the state of the given instance from the underlying database?

Ans:

Session.saveOrUpdate either saves(Object) or updates(Object) the given instance.




 

111. What are persistent classes in hibernate?

Ans:

Java classes whose objects or instances will be stored in database tables are called persistent classes in Hibernate.

112. What are the best practices that hibernate recommends for persistent classes.

Ans:

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 setXXX methods 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.

113. Where Object/relational mappings are defined in hibernate?

Ans:

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.

114. What is root node of hbm.xml?

Ans:

The mapping document is an XML document having as the root element which contains all < class> the elements.

115. Which element of hbm.xml defines a specific mappings from a Java classes to the database tables?

Ans:

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.

116. Which element of hbm.xml defines maps the unique ID attribute in class to the primary key of the database table?

Ans:

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.

117. Which element of hbm.xml is used to automatically generate the primary key values?

Ans:

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

118. Which element of hbm.xml is used to map a Java class property to a column in the database table?

Ans:

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

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

Ans:

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

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

Ans:

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.


 

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

Ans:

This is mapped with a < list> element and initialized with java.util.ArrayList.

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

Ans:

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

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

Ans:

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

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

Ans:

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.

125. What is many-to-one association?

Ans:

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

126. What is one-to-one association?

Ans:

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

127. What is one-to-many association?

Ans:

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.
element of set element indicates that one object relates to many other objects.

128. What is many-to-many association?

Ans:

A Many-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element.
element indicates that one object relates to many other objects and column attributes are used to link intermediate column.

129. Is SessionFactory a thread-safe object?

Ans:

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

130. Is Session a thread-safe object?

Ans:

No, Session is not thread-safe.



 

131. What is the difference between save() and persist() methods of session object?

Ans:

session.save saves the object and returns the id of the instance whereas persist do not return anything after saving the instance.

132. What is the difference between get() and load() methods of session object?

Ans:

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.

133. What is lazy loading?

Ans:

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.

134. What is HQL?

Ans:

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.