Hibernate Interview Questions And Answers For Experienced

44 Hibernate Interview Questions And Answers For Experienced from Codingcompiler. Test your Hibernate knowledge by answering these tricky interview questions on Java Hibernate. Let’s start learning Hibernate interview questions and prepare for Java Hibernate interviews. All the best for your future and happy learning.

Table of Contents

Hibernate Interview Questions

  1. What is the Hibernate Framework?
  2. What are the important benefits of using the Hibernate Framework?
  3. What are the advantages of Hibernate over JDBC?
  4. What are some important Hibernate interfaces?
  5. What is the Hibernate configuration file?
  6. What is a hibernate mapping file?
  7. What are some important annotations used to display in Hibernate.
  8. What do you know about Hibernate SessionFactory and how to configure it?
  9. Is Hibernate SessionFactory threadless?
  10. How to get Hibernate Session and what is it?
  11. Is the Hibernate Session thread safe?
  12. What is the difference between openSession and getCurrentSession?
  13. What is the difference between Hibernate Session get () and load () methods?
  14. What do you know about caching in Hibernate? Explain the concept of first-level cache in Hibernate?
  15. How to configure the second-level cache in Hibernate using EHCache?
  16. What are the different states of an entity bean?
  17. How is the Hibernate Session merge () method call used?
  18. What is the difference between save (), saveOrUpdate () and persist ()?
  19. What happens if an Entity Bean constructor with no arguments is missing?
  20. What is the difference between sorted collection and ordered collection? Which one is better?
  21. What types of collections in Hibernate do you know?
  22. How are Hibernate’s Join implemented?
  23. Why shouldn’t we make the Entity class final?
  24. What do you know about HQL and what are its advantages?
  25. What is Query Cache in Hibernate?
  26. Can we execute a native SQL query (sql native) in Hibernate?
  27. What are the advantages of supporting native sql in Hibernate?
  28. What is Named SQL Query?
  29. What are the benefits of Named SQL Query?
  30. Tell us about the benefits of using the Hibernate Criteria API.
  31. How to log generated Hibernate SQL queries to log files?
  32. What do you know about Hibernate proxy and how does it help in lazy load?
  33. How are relationships implemented in Hibernate?
  34. How to manage transactions using Hibernate?
  35. What are cascade links (updates) and what cascade types are there in Hibernate?
  36. How to add log4j logging to a hibernate application?
  37. How to use JNDI DataSource Application Server with Hibernate Framework?
  38. How to integrate Hibernate and Spring?
  39. What do you know about the HibernateTemplate class?
  40. How to integrate Hibernate with a Servlet or Struts2 web application?
  41. What patterns are used in Hibernate?
  42. Tell us about the Hibernate Validator Framework.
  43. What are the benefits of using the Hibernate Tools Eclipse plugin?
  44. Best Practices at Hibernate.

Hibernate Interview Questions And Answers

1. What is the Hibernate Framework?

Hibernate is a library for the Java programming language, designed to solve object-relational mapping (object-relational mapping – ORM) tasks. It is free open source software (open source), distributed under the GNU Lesser General Public License.

This library provides an easy-to-use framework (framework) for mapping an object-oriented data model to traditional relational databases. Hibernate is compatible with JSR-220/317 and provides standard JPA tools.

2. What are the important benefits of using the Hibernate Framework?

Hibernate is one of the most sought-after ORM frameworks for Java. And that’s why:

    1. Hibernate eliminates a lot of spaghetti (repetitive) code that constantly harasses a developer when working with JDBC. Hides from the developer a lot of code necessary for resource management and allows you to focus on business logic.
    1. Hibernate supports XML in the same way as JPA annotations, which makes the implementation of the code independent.
    1. Hibernate provides its own powerful query language (HQL), which is similar to SQL. It is worth noting that HQL is completely object-oriented and understands such principles as inheritance, polymorphism and associations (links).
    1. Hibernate is a widespread open source project. Thanks to this, thousands of open articles, examples, as well as documentation on the use of the framework are available.
    1. Hibernate seamlessly integrates with other Java EE frameworks, for example, the Spring Framework supports integrated integration with Hibernate.
    1. Hibernate supports lazy initialization using proxy objects and performs database queries only when necessary.
    1. Hibernate supports different levels of cache, and therefore can improve performance.
  1. It is important that Hibernate can use pure SQL, and therefore supports the ability to optimize queries and work with any third-party database vendor and its features.

3. What are the advantages of Hibernate over JDBC?

Hibernate has several advantages over the JDBC API:

    1. Hibernate removes a lot of duplicate code from the JDBC API, and therefore it is easier to read, write and maintain.
    1. Hibernate supports inheritance, associations, and collections, which is not available in the JDBC API.
    1. Hibernate implicitly uses transaction management. Most queries cannot be executed outside of a transaction. When using the JDBC API for transaction management, you need to explicitly use commit and rollback .
    1. JDBC API throws SQLException , which refers to the checked exceptions, which means you need to constantly write a lot of try-catchblocks  . In most cases, this is not necessary for every JDBC call and is used to manage transactions. Hibernate wraps JDBC exceptions through unchecked  JDBCException or  HibernateException , so there is no need to check them in the code every time. Hibernate’s built-in transaction management support removes try-catch blocks .
    1. Hibernate Query Language (HQL) is a more object-oriented and Java-like query language than SQL in JDBC.
    1. Hibernate supports caching, but JDBC requests do not, which can degrade performance.
    1. The Hibernate configuration allows you to use a JDBC like connection for the connection pool for the JNDI type DataSource. This is an important feature for enterprise applications, which is completely absent in the JDBC API.
  1. Hibernate supports JPA annotations, which means the code is portable to other ORM frameworks that implement the standard, while the JDBC code is strongly tied to the application.

4. What are some important Hibernate interfaces?

    1. SessionFactory (org.hibernate.SessionFactory) is an immutable thread-safe object with compiled mapping for one database. You need to initialize SessionFactory only once. A SessionFactory  instance is used to retrieve Session objects  that are used for database operations.
    1. Session (org.hibernate.Session)  is a single-threaded, short-lived object that provides a connection between application objects and a database. It wraps the JDBC java.sql.Connection and works as a factory for org.hibernate.Transaction . The developer must open the session as needed and close it immediately after use. A Session instance is an interface between code in a java application and the hibernate framework and provides methods for CRUD operations.
  1. Transaction (org.hibernate.Transaction)  is a single- stream short-lived object used for atomic operations. This is an abstraction of an application from basic JDBC or JTA transactions. org.hibernate.Session  can occupy several org.hibernate.Transaction  in certain cases.

5. What is the Hibernate configuration file?

The hibernate configuration file contains database data and is required for SessionFactory initialization. In the .xml file, you must specify the database vendor or JNDI resources, as well as information about the dialect used, which will help hibernate to choose the mode of operation with a specific database.

6. What is a hibernate mapping file?

A mapping file is used to link the entity beans and columns in a database table. In cases where JPA annotations are not used, the .xml mapping file may be useful (for example, when using third-party libraries).

7. What are some important annotations used to display in Hibernate.

Hibernate supports both annotations from JPA, and their own, which are in the package org.hibernate.annotations. The most important annotations are JPA and Hibernate:

    1. javax.persistence.Entity : used to specify a class as an entity bean.
    1. javax.persistence.Table : used to determine the name of the table from the database that will be displayed on the entity bean.
    1. javax.persistence.Access : defines the access type, field, or property. The field is the default value and if you want hibernate to use getter / setter methods, you must set them for the desired property.
    1. javax.persistence.Id : defines the primary key of the entity bean.
    1. javax.persistence.EmbeddedId : used to determine the composite key in a bean.
    1. javax.persistence.Column : defines the name of a column from a table in the database.
    1. javax.persistence.GeneratedValue : sets the key generation strategy. Used in conjunction with javax.persistence.GenerationType  enum.
    1. javax.persistence.OneToOne : sets up a one-to-one relationship between two entity beans. Accordingly, there are other annotations  OneToMany , ManyToOne and  ManyToMany .
    1. org.hibernate.annotations.Cascade : defines a cascade connection between two entity beans. Used in conjunction with org.hibernate.annotations.CascadeType .
  1. javax.persistence.PrimaryKeyJoinColumn : defines a foreign key for a property. Used with  org.hibernate.annotations.GenericGeneratorand  org.hibernate.annotations.Parameter .

8. What do you know about Hibernate SessionFactory and how to configure it?

SessionFactory is a class factory and is used to retrieve session objects. SessionFactory is responsible for reading the Hibernate configuration parameters and connecting to the database. Typically, an application has only one instance of SessionFactory, and threads that serve client requests receive session instances using the SessionFactory object. The internal state of SessionFactory is immutable. The internal state includes all the metadata about the Object / Relational Mapping and is set when the SessionFactory is created.

SessionFactory also provides methods for getting class metadata and statistics, such as data about the second level of the cache, running queries, etc.

9. Is Hibernate SessionFactory threadless?

Since Since the SessionFactory object is immutable (immutable), then yes, it is thread-safe. Multiple threads can access one object at a time.

Java Hibernate Interview Questions And Answers

10. How to get Hibernate Session and what is it?

The Hibernate Session object is a link between java application code and hibernate. This is the main interface for performing database operations. The life cycle of a session object is associated with the start and end of a transaction. This object provides methods for CRUD ( create , read , update , delete ) operations for the persistence object. With this instance, you can perform HQL, SQL queries and set the selection criteria.

11. Is the Hibernate Session thread safe?

The Hibernate Session object is not thread safe. Each thread must have its own Session object and close it at the end.

12. What is the difference between openSession and getCurrentSession?

Hibernate SessionFactory getCurrentSession () returns a session associated with the context. But in order for this to work, we need to configure it in the hibernate configuration file. Since this session object is associated with the hibernate context, there is no need to close it. The sessionobject closes with the closing of SessionFactory .

1 <property name=”hibernate.current_session_context_class”>thread</property>

The Hibernate SessionFactory openSession () method always creates a new session. We must control the closure of the session object after all operations with the database have been completed. For a multi-threaded environment, you must create a new session object for each request.

There is another openStatelessSession () method that returns a stateless session . Such an object does not implement the first level of caching and does not interact with the second level. This also includes ignoring collections and some event handlers. Such objects can be useful when loading large amounts of data without retaining a large amount of information in the cache.

13. What is the difference between Hibernate Session get () and load () methods?

Hibernate session has various methods for loading data from a database. The most commonly used methods for this are get () and load () .

    • get () loads data immediately when called, while load () uses a proxy object and loads data only when it is actually required. In this regard, load () has the advantage of lazy loading of data.
    • load () throws an exception when no data is found. Therefore, it should be used only with confidence in the existence of data.
  • You need to use the get () method  if you need to verify the availability of data in the database.

14. What do you know about caching in Hibernate? Explain the concept of first-level cache in Hibernate?

Hibernate uses caching to make our application faster. Hibernate cache can be very helpful in getting high performance applications when used properly. The idea of ​​caching is to reduce the number of queries to the database.

Hibernate level 1 cache is associated with a Session object. Hibernate level one cache is enabled by default and there is no way to disable it. However, Hibernate provides methods by which we can delete selected objects from the cache or completely clear the cache.

Any object cached in session will not be visible to other session objects. After the session object is closed, all cached objects will be lost.

Advanced Hibernate Interview Questions And Answers

15. How to configure the second-level cache in Hibernate using EHCache?

EHCache is the best choice for organizing second-level caching in Hibernate. To configure the second level of caching in Hiberate, several steps are required.

  • Add the hibernate-ehcache dependency to the project.
1

2

3

4

5

<dependency>

       <groupId>org.hibernate</groupId>

       <artifactId>hibernate-ehcache</artifactId>

       <version>4.3.5.Final</version>

</dependency>

  • Add multiple entries to the hibernate configuration file.
1

2

3

4

5

6

7

8

9

10

<property name=”hibernate.cache.region.factory_class”>org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

         

<!– For singleton factory –>

<!– <property name=”hibernate.cache.region.factory_class”>org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property>

–>

      

<!– enable second level cache and query cache –>

<property name=”hibernate.cache.use_second_level_cache”>true</property>

<property name=”hibernate.cache.use_query_cache”>true</property>

<property name=”net.sf.ehcache.configurationResourceName”>/myehcache.xml</property>

  • Create an EHCache configuration file.
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<?xml version=”1.0″ encoding=”UTF-8″?>

<ehcache xmlns:xsi=”https://www.w3.org/2001/XMLSchema-instance”

   xsi:noNamespaceSchemaLocation=”ehcache.xsd” updateCheck=”true”

   monitoring=”autodetect” dynamicConfig=”true”>

 

   <diskStore path=”java.io.tmpdir/ehcache” />

 

   <defaultCache maxEntriesLocalHeap=”10000″ eternal=”false”

       timeToIdleSeconds=”120″ timeToLiveSeconds=”120″ diskSpoolBufferSizeMB=”30″

       maxEntriesLocalDisk=”10000000″ diskExpiryThreadIntervalSeconds=”120″

       memoryStoreEvictionPolicy=”LRU” statistics=”true”>

       <persistence strategy=”localTempSwap” />

   </defaultCache>

 

   <cache name=”employee” maxEntriesLocalHeap=”10000″ eternal=”false”

       timeToIdleSeconds=”5″ timeToLiveSeconds=”10″>

       <persistence strategy=”localTempSwap” />

   </cache>

 

   <cache name=”org.hibernate.cache.internal.StandardQueryCache”

       maxEntriesLocalHeap=”5″ eternal=”false” timeToLiveSeconds=”120″>

       <persistence strategy=”localTempSwap” />

   </cache>

 

   <cache name=”org.hibernate.cache.spi.UpdateTimestampsCache”

       maxEntriesLocalHeap=”5000″ eternal=”true”>

       <persistence strategy=”localTempSwap” />

   </cache>

</ehcache>

  • Use @Cache annotation and specify caching strategy over entity bean.
1

2

3

4

5

6

7

8

9

import org.hibernate.annotations.Cache;

import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity

@Table(name = “ADDRESS”)

@Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region=”employee”)

public class Address {

}

16. What are the different states of an entity bean?

    1. Transient : a state in which the object has never been associated with any session and is not persistence. This object is in a temporary condition. An object in this state can become persistent by calling the  save () , persist (), or  saveOrUpdate () methods . The persistence object can go to the transient state after calling the delete () method .
    1. Persistent : when an object is associated with a unique session, it is in a persistent state . Any instance returned by get () or load () is in a persistent state  .
  1. Detached : if the object was persistent, but is not associated with any session now, then it is in the detached state. Such an object can be made persistent using the update () , saveOrUpdate () , lock () or  replicate () methods . The  transient or  detached states can also go into the persistent state as a new persistence object after calling the merge () method  .

17. How is the Hibernate Session merge () method call used?

Hibernate merge ()  can be used to update existing values, but this method creates a copy from the passed entity object and returns it. The returned object is part of the persistence context and tracks any changes, and the transferred object is not tracked.

18. What is the difference between save (), saveOrUpdate () and persist ()?

Hibernate save () is used to save an entity to the database. The problem with using the save () method is that it can be called without a transaction. Therefore, if we have a display of several objects, then only the primary object will be saved and we will get inconsistent data. Also save () returns the generated id immediately.

Hibernate persist () is  similar to save () with a transaction. persist () does not return the generated id immediately.

Hibernate saveOrUpdate () uses a query to insert or update based on the data provided. If the data is already present in the database, the update request will be executed. The saveOrUpdate () method  can be used without a transaction, but this can lead to similar problems as with the save () method .

19. What happens if an Entity Bean constructor with no arguments is missing?

Hibernate uses reflection to create instances of an Entity bean when calling get () or load () methods . To do this, use the Class.newInstance ()method , which requires a constructor without parameters. Therefore, in case of its absence, you will get an error HibernateException.

Spring Hibernate Interview Questions And Answers

20. What is the difference between sorted collection and ordered collection? Which one is better?

If you are using from the Collection API sorting algorithms sorted list (used for sorting the collection of the sorted list ). For small collections, this does not lead to waste of resources, but on large collections this can lead to loss of performance and OutOfMemory errors . The same entity beans must implement the Comparable or Comparator interface for working with sorted collections.

When using the Hibernate framework to load data from a database, we can use the Criteria API and the order by command to get the ordered list . Ordered list is the best choice to sorted list , because it uses database level sorting. It is faster and cannot cause a memory leak. An example of a query to the database to get the ordered list :

1

2

List<Employee> empList = session.createCriteria(Employee.class)

                       .addOrder(Order.desc(“id”)).list();

21. What types of collections in Hibernate do you know?

    1. Bag
    1. Set
    1. List
    1. Array
  1. Map

22. How are Hibernate’s Join implemented?

There are several ways to implement links in Hibernate.

    • Use associations such as  one-to-one , one-to-many , many-to-many .
    • Use the JOIN command in the HQL query . There is another form of ” join fetch ” that allows you to load data immediately (not lazy).
  • Use pure SQL query with the join command .

23. Why shouldn’t we make the Entity class final?

Hiberneit uses proxy classes for lazy loading of data (that is, as needed, not immediately). This is achieved by extending the entity bean and, therefore, if it were final , it would be impossible. Lazy loading of data in many cases improves performance, and therefore is important.

24. What do you know about HQL and what are its advantages?

Hibernate Framework comes with a powerful object-oriented query language – Hibernate Query Language (HQL). It is very similar to SQL, except that it uses objects instead of table names, which makes the language closer to object-oriented programming.

HQL is case-insensitive, except for using java names and variables in queries, where it obeys Java rules. For example, SelECt is the same as select , but en.javastudy.MyClass is different from  en.javastudy . MyCLASS . HQL queries are cached (this is both a plus and a minus).

25. What is Query Cache in Hibernate?

Hibernate implements a cache area for resultset queries , which closely interacts with the Hibernate second-level cache. To connect this additional function requires several additional steps in the code. Query Cache is useful only for frequently executed queries with duplicate parameters. First you need to add this entry in the Hibernate configuration file:

1 <property name=”hibernate.cache.use_query_cache”>true</property>

Already within the application code, the setCacheable (true) method is used for the request  , as shown below:

1

2

3

Query query = session.createQuery(“from Employee”);

query.setCacheable(true);

query.setCacheRegion(“ALL_EMP”);

26. Can we execute a native SQL query (sql native) in Hibernate?

Using SQLQuery, you can perform a pure SQL query. In general, this is not recommended, since you lose all the benefits of HQL (associations, caching). You can do something like this:

1

2

3

4

5

6

7

8

9

10

Transaction tx = session.beginTransaction();

SQLQuery query = session.createSQLQuery(“select emp_id, emp_name, emp_salary from Employee”);

List<Object[]> rows = query.list();

for(Object[] row : rows){

   Employee emp = new Employee();

   emp.setId(Long.parseLong(row[0].toString()));

   emp.setName(row[1].toString());

   emp.setSalary(Double.parseDouble(row[2].toString()));

   System.out.println(emp);

}

27. What are the advantages of supporting native sql in Hibernate?

Using native SQL may be necessary when running queries against some databases that may not be supported in Hibernate. An example is some specific queries and “chips” when working with a database from Oracle.

28. What is Named SQL Query?

Hibernate supports a named query that we can specify in a central place and then use it anywhere in the code. Named queries support both HQL and Native SQL. You can create a named query using JPA annotations  @NamedQuery ,  @NamedNativeQuery or in the mapping files.

29. What are the benefits of Named SQL Query?

Hibernate named query allows you to collect multiple queries in one place, and then call them in any class. The Named Query syntax is checked when creating a session factory, which allows you to notice an error at an early stage, and not when the application is running and the query is executed. Named Query global, i.e. once set, can be used anywhere.

However, one of the main disadvantages of a named query is that it is very difficult to debug it (there may be difficulties with finding a place to define a query).

Hibernate Interview Questions And Answers For Experienced

30. Tell us about the benefits of using the Hibernate Criteria API.

The Hibernate Criteria API is more object-oriented for queries that get results from a database. For update, delete, or other DDL manipulation operations, you cannot use the Criteria API. Criteria are used only to select from a database in a more object-oriented style.

Here are some of the uses of the Criteria API:

    • The Criteria API supports projection, which we can use for aggregate functions like sum () , min () , max () , etc.
    • The Criteria API can use  ProjectionList to extract data only from selected columns.
    • The Criteria API can be used to join queries by joining multiple tables using the  createAlias ​​() , setFetchMode () and  setProjection () methods .
    • The Criteria API supports fetching results according to conditions (restrictions). To do this, use the add () method with which Restrictions are added.
  • The Criteria API allows you to add order (sorting) to the result using the addOrder () method.

31. How to log generated Hibernate SQL queries to log files?

To log SQL queries, add the following line to the Hibernate configuration file:

1 <property name=”hibernate.show_sql”>true</property>

Note that this should be used at the Development or Testing level and should be disabled in production.

32. What do you know about Hibernate proxy and how does it help in lazy load?

Hibernate uses a proxy object to support deferred loading. Normally, when loading data from a table, Hibernate does not load all of the mapped (zamappinny) objects. As soon as you refer to a child object or search for an object using a getter, if the associated entity is not in the session cache, then the proxy code will go to the database to load the related entity. For this, javassist is used to effectively and dynamically create implementations of the subclasses of your entity objects.

33. How are relationships implemented in Hibernate?

You can implement the one-to-one , one-to-many , many-to-many relationship using JPA annotations or configuring an xml file.

34. How to manage transactions using Hibernate?

Hibernate does not allow most transactions at all without the use of transactions. Therefore, after receiving a session instance from SessionFactory , beginTransaction () must be executed to start the transaction. The method will return a link that we can use to confirm or roll back the transaction.

In general, the management of transactions in the framework is much better than in JDBC, because we should not rely on the occurrence of an exception to roll back a transaction. Any exception will automatically cause rollback.

35. What are cascade links (updates) and what cascade types are there in Hibernate?

If we have dependencies between entities, we need to determine how different operations will affect another entity. This is implemented using cascading links (or updates). Here is a sample code using the @Cascade annotation :

1

2

3

4

5

6

7

8

9

10

11

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 there are some differences between enum CascadeType in Hibernate and in JPA. Therefore, pay attention to which package you import when using annotations and type constants. The most commonly used CascadeType enums are described below.

    1. None : no cascading. Formally, this is not a type, but if we have not specified a cascade connection, then no operation for the parent will have an effect on the child.
    1. ALL : Cascades save, delete, update, evict, lock, replicate, merge, persist. Well, that’s all.
    1. SAVE_UPDATE : Cascades save and update. Only available for hibernate.
    1. DELETE : sends an  action to Hibernate native DELETE . Only for hibernate.
    1. DETATCH , MERGE , PERSIST , REFRESH and  REMOVE – for simple operations.
    1. LOCK : sends an  action to Hibernate native LOCK .
  1. REPLICATE : sends an  action to Hibernate native REPLICATE .

36. How to add log4j logging to a hibernate application?

    • Add log4j dependency to the project.
    • Create a log4j.xml or log4j.properties file and add it to the classpath.
    • For web applications, use ServletContextListener, and for standalone applications, DOMConfigurator or PropertyConfigurator to configure logging.
  • Create an instance of org.apache.log4j.Logger and use it according to the task.

37. How to use JNDI DataSource Application Server with Hibernate Framework?

In a web application, it is best to use a servlet container to manage a pool of connections. Therefore, it is better to define a JNDI resource for the DataSource and use it in a web application. To do this, in Hibernate, you need to remove all database-specific properties and use the JNDI DataSource property indications:

1 <property name=”hibernate.connection.datasource”>java:comp/env/jdbc/MyLocalDB</property>

38. How to integrate Hibernate and Spring?

It is best to read about the settings on the framework sites for the current version. Both frameworks support integration out of the box and in general setting up their interaction is easy. The general steps are as follows.

    • Add dependencies for hibernate entitymanager, hibernate-core and spring-orm.
    • Create model classes and transfer to the DAO implementation database operations. It is important that the DAO classes use SessionFactory, which is embedded in the configuration of Spring beans.
    • Configure the Spring configuration file (see the offsite documentation or from the example on this site).
  • Additionally, it is possible to use the @Transactional annotation and stop worrying about managing the Hibernate transaction.

39. What do you know about the HibernateTemplate class?

The Spring Framework provides various approaches for integrating with Hibernate. However, we will most often use an approach that uses the HibernateTemplate. There are two main reasons:

    • The class hides the details of managing sessions and transactions.
  • Provides a template-based approach.

The HibernateTemplate class hides the difficulties of managing sessions and transactions when using Hibernate to access data. You only need to initialize the HibernateTemplate by passing the SessionFactory instance. The Spring Framework takes care of the details associated with sessions and transactions. This helps to eliminate the infrastructure code, which can cause clutter with increasing complexity.

HibernateTemplate, as well as JdbcTemplate, provides a template approach for data access. When you use the HibernateTemplate, you will work with callbacks. Callbacks are the only mechanism in the template approach that notifies the template to run the desired task. The advantage of having a callback is that there is only one entry point to the data access layer. And this entry point is determined by the template, in this case HibernateTemplate.

In the comments added that the use of HibernateTemplate is not recommended. Instead of using the hibernateTemplate from the org.springframework.orm package, we recommend using the declarative approach (@Transactional). Thus, the framework will take care of the open, commit, close, flush operations.

Hibernate Interview Questions And Answers For Java Developers

40. How to integrate Hibernate with a Servlet or Struts2 web application?

For integration, you must use a ServletContextListener. For a more detailed example, see the link.

https://www.journaldev.com/3557/struts2-hibernate-integration-example-tutorial

41. What patterns are used in Hibernate?

    • Domain Model Pattern is an object model of the subject area, including both behavior and data.
    • Data Mapper is a layer of mappers that transfers data between objects and a database, keeping them independent of each other and of themselves.
    • Proxy Pattern – used for lazy loading.
  • Factory pattern – used in SessionFactory

42. Tell us about the Hibernate Validator Framework.

Data validation is an integral part of any application. Hibernate Validator provides a reference implementation of the two JSR-303 and JSR-349 specifications used in Java. To configure validation in Hibernate, you need to do the following steps.

  • Add hibernate validation dependencies to the project.
1

2

3

4

5

6

7

8

9

10

<dependency>

   <groupId>javax.validation</groupId>

   <artifactId>validation-api</artifactId>

   <version>1.1.0.Final</version>

</dependency>

<dependency>

   <groupId>org.hibernate</groupId>

   <artifactId>hibernate-validator</artifactId>

   <version>5.1.1.Final</version>

</dependency>

  • It also requires dependencies from JSR 341 that implement Unified Expression Language to handle dynamic expressions and constraint violation messages.
1

2

3

4

5

6

7

8

9

10

<dependency>

   <groupId>javax.el</groupId>

   <artifactId>javax.el-api</artifactId>

   <version>2.2.4</version>

</dependency>

<dependency>

   <groupId>org.glassfish.web</groupId>

   <artifactId>javax.el</artifactId>

   <version>2.2.4</version>

</dependency>

  • Use required annotations in bins.
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

import javax.validation.constraints.Min;

import javax.validation.constraints.NotNull;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.CreditCardNumber;

import org.hibernate.validator.constraints.Email;

public class Employee {

   @Min(value=1, groups=EmpIdCheck.class)

   private int id;

   @NotNull(message=”Name cannot be null”)

   @Size(min=5, max=30)

   private String name;

   @Email

   private String email;

   @CreditCardNumber

   private String creditCardNumber;

….

43. What are the benefits of using the Hibernate Tools Eclipse plugin?

The Hibernate Tools plugin makes it easy to set up a mapping configuration file. Simplifies working with properties files or xml tags. Helps minimize spelling errors.

44. Best Practices at Hibernate.

When using the Hibernate framework, it is recommended to follow some rules.

    • Always check access to the primary key. If it is created by a database, then you should not have a setter.
    • By default, hibernate sets values ​​to fields directly without using setters. If you need to force the hibernate to apply them, then check the use of the @Access annotation  (value = AccessType.PROPERTY) on the property.
    • If the access type is property, then make sure the annotation is used with the getter. Avoid mixing annotation usage over both fields and the getter.
    • Use the native sql query only where HQL cannot be used.
    • Use the ordered list instead of the sorted list from the Collection API if you need to get the sorted data.
    • Use named queries wisely – keep them in one place and use only for frequently used queries. For specific queries, write them inside a specific bean.
    • In web applications, use the JNDI DataSource instead of the configuration file to connect to the database.
    • Avoid many-to-many relationships because this can be replaced with a bidirectional One-to-Many and Many-to-One link.
    • For collections, try using Lists, maps, and sets. Avoid arrays, because they do not give the advantage of lazy loading.
    • Do not handle exceptions that can roll back a transaction and close a session. If this is ignored, then Hibernate cannot guarantee that the state in memory corresponds to the state of persistence (there may be data collisions).
    • Use the DAO pattern for methods that can be used in entity beans.
  • Prefer lazy sampling for associations.

Must Read Java Interview Questions Books 2020

RELATED INTERVIEW QUESTIONS

  1. Hibernate Questions And Answers
  2. JPA Interview Questions and Answers
  3. Spring Framework Interview Questions
  4. Spring Boot Interview Questions
  5. GIT Interview Questions And Answers
  6. Network Security Interview Questions
  7. CheckPoint Interview Questions
  8. Page Object Model Interview Questions
  9. Apache Pig Interview Questions
  10. Python Interview Questions And Answers
  11. Peoplesoft Integration Broker Interview Questions
  12. PeopleSoft Application Engine Interview Questions
  13. RSA enVision Interview Questions
  14. RSA SecurID Interview Questions
  15. Archer GRC Interview Questions
  16. RSA Archer Interview Questions
  17. Blockchain Interview Questions
  18. Commvault Interview Questions
  19. Peoplesoft Admin Interview Questions
  20. ZooKeeper Interview Questions
  21. Apache Kafka Interview Questions
  22. Couchbase Interview Questions
  23. IBM Bluemix Interview Questions
  24. Cloud Foundry Interview Questions
  25. Maven Interview Questions
  26. VirtualBox Interview Questions
  27. Laravel Interview Questions
  28. Logstash Interview Questions
  29. Elasticsearch Interview Questions
  30. Kibana Interview Questions
  31. JBehave Interview Questions
  32. Openshift Interview Questions
  33. Kubernetes Interview Questions

Leave a Comment