Top Interview Questions & Answers | Learn Now

Best Hibernate Interview Questions and Answers 2018

Written by Bhavya Sri | May 27, 2017 6:45:38 AM

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

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

Q3. 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 as in the below example:

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

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

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

Q7. 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:

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.

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

Q10. How can we invoke stored procedures in hibernate?

Ans: In hibernate we can execute stored procedures using code as below:

[xml]

<sql-query name=”getStudents” callable=”true”>
<return alias=”st” class=”Student”>
<return-property name=”std_id” column=”STD_ID”/>
<return-property name=”s_name” column=”STD_NAME”/>
<return-property name=”s_dept” column=”STD_DEPARTMENT”/>
{ ? = call selectStudents() }
</return>
</sql-query>

[/xml]

Q11. What is criteria API?

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

Q12. What are the benefits of using Hibernate template?

Ans: Following are some key benefits of using Hibernate template:

  • Session closing is automated.
  • Interaction with hibernate session is simplified.
  • Exception handling is automated.

Q13. How can we see hibernate generated SQL on console?

Ans: We need to add following in hibernate configuration file to enable viewing SQL on the console for debugging purposes:

[xml]

<property name=”show_sql”>true</property>

[/xml]

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

Ans: Following are the two types of collections in hibernate:

  • Sorted Collection
  •  Order Collection

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

Q16. What the benefits are of hibernate over JDBC?

Ans:

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

Q17. How can we get hibernate statistics?

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

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

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

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

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

Q22. What the four ORM levels are in hibernate?

Ans: Following are the four ORM levels in hibernate:

  • Pure Relational
  • Light Object Mapping
  • Medium Object Mapping
  • Full Object Mapping

Q23. 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();
}

[/java]

Q24. What the two methods are of hibernate configuration?

Ans: We can use any of the following two methods of hibernate configuration:

  • XML based configuration ( using hibernate.cfg.xml file)
  • Programmatic configuration ( Using code logic)

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

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

Ans: In hibernate; we have following two types of mapping associations between entities:

  • One-to-One Association
  • Many-to-Many Association

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

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

Ans: Hibernate provides following four ways to fetch objects from database:

  • Using HQL
  • Using identifier
  • Using Criteria API
  • Using Standard SQL

Q29. How primary key is created by using hibernate?

Ans: Database primary key is specified in the configuration file hbm.xml. Generator can also be used to specify how primary key is being created in the database.
In the below example, deptId acts as primary key:

[xml]
<id name=”deptId” type=”string” >
<column name=”columnId” length=”30″/>
<generator/>
</id>
[/xml]

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

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

Ans: Hibernate second level cache can be disabled using any of the following ways:

  • By setting use_second_level_cache as false.
  • By using CACHEMODE.IGNORE.
  • Using cache provider as org.hibernate.cache.NoCacheProvider

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

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

Ans: With hibernate 3.2, default transaction factory is JDBCTransactionFactory.

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

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

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

Ans: Object identification can be done in hibernate in following three ways:

  • Using Object Identity: Using == operator.
  • Using Object Equality: Using equals() method.
  • Using database identity: Relational database objects can be identified if they represent same row.

Q37. What different fetching strategies are of hibernate?

Ans: Following fetching strategies are available in hibernate:

  • Join Fetching
  • Batch Fetching
  • Select Fetching
  • Sub-select Fetching

Q38. How mapping of java objects is done with database tables?

Ans: To map java objects with database tables, we need to have Java beans properties names same as column names of a database table. Then mapping is provided in hbm.xml file as given below:

[xml]
<hibernate-mapping>
<class name=”Student”  table=”tbl_student”>
<property  column=”studentname” length=”255″
name=”studentName” not-null=”true”  type=”java.lang.String”/>
<property  column=”studentDisciplne” length=”255″
name=”studentDiscipline” not-null=”true”  type=”java.lang.String”/>
</class>
</hibernate-mapping>
[/xml]

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

Q40. 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:

[xml]

<sql-query name = “studentdetails”>
<return alias=”std”/>
SELECT std.STUDENT_ID AS {std.STUDENT_ID},
std.STUDENT_DISCIPLINE AS {std.discipline},

FROM Student std WHERE std.NAME LIKE :name
</sql-query>

[/xml]

Then this query can be called as follows:

[java]

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

[/java]

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

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

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

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

Q45. Does hibernate support polymorphism?

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

Q46. What the three inheritance models are of hibernate?

Ans: Hibernate has following three inheritance models:

  • Tables Per Concrete Class
  • Table per class hierarchy
  • Table per sub-class

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

Q48. What’s general hibernate flow using RDBMS?

Ans: General hibernate flow involving RDBMS is as follows:

  • Load configuration file and create object of configuration class.
  • Using configuration object, create sessionFactory object.
  • From sessionFactory, get one session.
  • Create HQL query.
  • Execute HQL query and get the results. Results will be in the form of a list.

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

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