Corporate Training
Request Demo
Menu
Let's Talk
Request Demo

Hibernate Interview Questions and Answers

by Mohammed, on Mar 15, 2018 4:50:45 PM

 

Hibernate Interview Questions and Answers

Q1. What is Hibernate?

Ans: Hibernate is an ORM (Object-relational Mapping) framework, which allows the developer to concentrate on business logic by taking care of persistence of data by itself. Java developer can write code using object and Hibernate can take care of creating those object from data loaded from the database and saving update back to the database.

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

Q4. What are the advantages of using Hibernate?

Ans: Below 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.

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

Q6. What are the advantages of Hibernate over JDBC? 

Ans: Apart from Persistence i.e. saving and loading data from Database, Hibernate also provides following benefits
Caching
Lazy Loading
Relationship management and provides code for mapping an object to the data
The developer is free from writing code to load/store data into the database

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:

Java:

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

 

Q8. What is N+1 SELECT problem in Hibernate? 

Ans: The N+1 SELECT problem is a result of lazy loading and load on demand fetching strategy. In this case, Hibernate ends up executing N+1 SQL queries to populate a collection of N elements. For example, if you have a List of N Items where each Item has a dependency on a collection of Bid object. Now if you want to find the highest bid for each item then Hibernate will fire 1 query to load all items and N subsequent queries to load Bid for each item. So in order to find the highest bid for each item your application end up firing N+1 queries.

Q9. What is the requirement for a Java object to become Hibernate entity object? 

Ans: It should not be final and must provide a default, no-argument constructor. See the detailed answer to learn more about the special requirement for a Java object to become Hibernate Entity.

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

Q11. Mention 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.

Q12. List out the four ORM levels  in hibernate?

Ans: Following are the four ORM levels in hibernate:

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

Q13.  What are different types of caches available in Hibernate? 

Ans: This is another common Hibernate interview question. Hibernate provides the out-of-box caching solution but there are many caches e.g. first level cache, second level cache and query cache. First level cache is maintained at Session level and cannot be disabled but the second level cache is required to be configured with external cache provider like EhCache.

Q14. What is criterion query in hibernate? 

Ans: Criteria is a simplified API for retrieving entities by composing Criterion objects also known as Criterion query. This is a very convenient approach for functionality like "search" screens where you can filter data on multiple conditions as shown in the following example:

List books = session.createCriteria(Book.class) .add(Restrictions.like("name", "java%") ) .add(Restrictions.like("published_year", "2015")) .addOrder(Order.asc("name") ) .list();

This can be a tough question if you are not using Hibernate on a daily basis, I have interviewed several Java developers who have used Hibernate but doesn't know about Criterion query or API.

Q15. What are other ORM frameworks? Any alternative of Hibernate?

Ans: This is a general question, sometimes asked to start the conversation and other times to finish the interview. EJB and TopLink from Oracle are two of the most popular alternative to Hibernate framework.

Q16. What is the difference between save() and saveOrUpdate() method of Hibernate? 

Ans: Though both save() and saveOrUpdate() method is used to store object into Database, the key difference between them is that save can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records.

Q17. What is difference between getCurrentSession() and openSession() in Hibernate? 

Ans: An interesting Hibernate interview question as you might have used both getCurrentSession() and openSession() to obtain an instance of Session object. I have left this question unanswered for you to answer or find an answer based on your experience.

Q18. What is the difference between first and second level cache in Hibernate? 

Ans: This is again follow-up of previous Hibernate interview question. The first level cache is maintained at Session level while the second level cache is maintained at SessionFactory level and shared by all sessions.

Q19. Does Hibernate Session interface is thread-safe in Java? 

Ans: No, Session object is not thread-safe in Hibernate and intended to be used with-in single thread in the application.

Q20. Does SessionFactory is thread-safe in Hibernate? 

Ans: SessionFactory is both Immutable and thread-safe and it has just one single instance in Hibernate application. It is used to create Session object and it also provide caching by storing SQL queries stored by multiple session. The second level cache is maintained at SessionFactory level. This can be a difficult and tricky question for less experienced Java developers who are not familiar with thread-safety and Immutability.

Q21. What is different between Session and Sessionfactory in Hibernate?

Ans: This is another popular Hibernate interview question, mostly at a telephonic round of interviews. The main difference between Session and SessionFactory is that former is a single-threaded, short-lived object while later is Immutable and shared by all Session. It also lives until the Hibernate is running. Another difference between Session and SessionFactory is that former provides first level cache while SessionFactory provides the Second level cache.

Q22. What is Hibernate Query Language (HQL)? 

Ans: Hibernate query language, HQL is an object-oriented extension to SQL. It allows you to query, store, update, and retrieve objects from a database without using SQL. This question is also similar to the earlier question about Criterion query, Java developers who have not used Hibernate extensively will not know much about features like HQL and Criterion.

Q23. When do you use merge() and update() in Hibernate? 

Ans: This is one of the tricky Hibernate interview questions. You should use update() if you are sure that the Hibernate session does not contain an already persistent instance with the same id and use merge() if you want to merge your modifications at any time without considering the state of the session.

Q24. The difference between sorted and ordered collection in Hibernate? 

Ans: The main difference between sorted and ordered collection is that sorted collection sort the data in JVM's heap memory using Java's collection framework sorting methods while ordered collection is sorted using order by clause in the database itself. A sorted collection is more suited for small dataset but for a large dataset, it's better to use ordered collection to avoid OutOfMemoryError in Java application.

Q25. How do you log SQL queries issued by the Hibernate framework in Java application?

Ans: You can use the show_sql property to log SQL queries issued by the Hibernate framework, Just add the following line in your Hibernate configuration file:

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

Q26. What are the three states of a Hibernate Persistence object can be? 

Ans: The Hibernate persistent or entity object can live in following three states:

  1. transient
  2.  persistent
  3.  detached

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

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

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

Q30. What is the difference between the transient, persistent and detached state in Hibernate? 

Ans: New objects created in Java program but not associated with any hibernate Session are said to be in the transient state. On the other hand, an object which is associated with a Hibernate session is called Persistent object. While an object which was earlier associated with Hibernate session but currently it's not associate is known as a detached object. You can call save() or persist() method to store those object into the database and bring them into the Persistent state. Similarly, you can re-attach a detached object to hibernate sessions by calling either update() or saveOrUpdate() method.

Q31. Which cache is used by Session Object in Hibernate? First level or second level cache? 

Ans: A Session object uses the first-level cache. As I told before the second level cache is used at SessionFactory level. This is a good question to check if Candidate has been working in hibernate or not. If he has not worked in Hibernate from a long time then he would get confused in this question.

Q32. What different fetching strategies are of hibernate?

Ans: Following fetching strategies are available in hibernate:

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

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

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

Q35. Does hibernate support polymorphism?

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

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

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

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

Topics:Hibernate Interview Questions and AnswersInformation Technologies (IT)

Comments

Subscribe

Top Courses in Python

Top Courses in Python

We help you to choose the right Python career Path at myTectra. Here are the top courses in Python one can select. Learn More →

aathirai cut mango pickle

More...