Hibernate Interview Questions

  1. What is JPA? How is Hibernate related to JPA?
  2. What is Hibernate? What does it help a programmer do?
  3. Explain high level architecture of Hibernate framework?
  4. Can you give an example of an Entity mapping with Hibernate?
  5. How do you indicate to Hibernate that a table will not be updated through the application?
  6. How can you generate a unique identifier using Hibernate?
  7. What is optimistic locking? How can you use it with Hibernate?
  8. How do you implement single table per class hierarchy strategy with Hibernate?
  9. How do you implement table per class strategy with Hibernate?
  10. How do you specify a one to many unidirectional relationship with Hiberate?
  11. How do you specify a one-to-many bidirectional relationship with Hibernate?
  12. How do you implement pagination with Hibernate?
  13. What is a lazy association?
  14. What is N + 1 selects Problem in hibernate?
  15. How can you do automatic schema generation from Hibernate Mappings?
  16. What is the use of SchemaValidator?
  17. Suggest some Hibernate Best Practices?

What is JPA? How is Hibernate related to JPA?

JPA (Java Persistence API) is a specification of how the object relational mapping should be done. Java is an object oriented programming language. Data from java objects need to be stored in relational (sql based) tables. JPA defines the specification (interface) of how the mapping should be done. JPA is just a specification with no implementation. Hibernate is an implementation of the JPA specification. All annotations specified by JPA are implemented by Hibernate. The main benefit of using JPA is that at a later point in time, you can easily switch to another implementation of JPA (different from Hibernate). If I directly use Hibernate annotations, I'm locked in to Hibernate. I cannot easily switch to another ORM framework.

What is Hibernate? What does it help a programmer do?

Hibernate is an ORM framework. An object relational mapping framework.

Java is an object oriented programming language. Data from java objects need to be stored in relational (sql based) tables. Traditionally , this is done using sql queries. Hibernate provides an alternative way of storing data from Java objects into a relational database.

Explain high level architecture of Hibernate framework?

Below picture shows the important components in Hibernate architecture.

SessionFactory (org.hibernate.SessionFactory) : A cache of compiled mappings (hbm’s or annotation based) for a single database.

Session (org.hibernate.Session) : Represents a conversation between the java application and the persistent store. It is a wrapper around JDBC java.sql.Connection.

Persistent objects : JavaBeans/POJOs with the persistent state and business function associated with one org.hibernate.Session.

Transaction (org.hibernate.Transaction): Used by Java application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction.

Can you give an example of an Entity mapping with Hibernate?

See example below:

@Entity
@Table(name="TBL_PERSON", 
           uniqueConstraints=
           @UniqueConstraint(
               name="person_id", 
               columnNames={"name", "person_id"} ) )

public class Person implements Serializable {
    @Column(name="name")
    public String getName() { return name; }

    @Column(name="person_id")
    public String getId() { return id; }
}

How do you indicate to Hibernate that a table will not be updated through the application?

In application, there would generally exist tables which are not updated through the application directly. Typical examples would be master data tables containing list of Countries or States. We can use the @Immutable annotation to indicate to Hibernate that a table will not be updated from the application. This allows Hibernate to make some minor performance optimizations.

How can you generate a unique identifier using Hibernate?

Hibernate can create identifier values automatically. There are several identifier generation strategies. Some of them are discussed below

  • IDENTITY: supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HSQL.
  • SEQUENCE: Uses a named database sequence to generate identifiers.
  • CUSTOM GENERATOR : Write your own logic.
  • AUTO: selects one of the above based on the database.

To mark an id property as generated, use the @GeneratedValue annotation.

   @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
   Integer getId() { ... };

Another Example using a Sequence:

@GeneratedValue(
    strategy=GenerationType.SEQUENCE, 
    generator="SEQ_GEN")
   Integer getId() { ... };

What is optimistic locking? How can you use it with Hibernate?

In applications which have long running transactions, optimistic locking might provide required scalability. Without optimistic locking, the tables might be locked avoiding concurrent access.

Hibernate provides two approaches to optimistic locking: version number or timestamp. Using a version number is preferred approach. It is implemented using @Version annotation. Entity manager would use the LOCKING_COLUMN to detect conflicting updates.

    @Version
    @Column(name="LOCKING_COLUMN")
    public Integer getVersion() { ... }

How do you implement single table per class hierarchy strategy with Hibernate?

Below example shows how to configure single table per class hierarchy strategy using Annotations in Hibernate. The important annotations used are @DiscriminatorColumn and @DiscriminatorValue.

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name="cartype",
    discriminatorType=DiscriminatorType.STRING
)

@DiscriminatorValue("Car")
public class Car { ... }

@Entity
@DiscriminatorValue("Formula1")
public class FormulaOneCar extends Car { ... }

How do you implement table per class strategy with Hibernate?

Table per class strategy is the default strategy for Hibernate. If you want to be explicit, you can use the annotations shown in the example below.

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Car implements Serializable { ... }

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class FormulaOneCar implements Serializable { ... }

How do you specify a one to many unidirectional relationship with Hiberate?

Example below shows how to implement this relationship using Annotations. Key annotation is @OneToMany.

public class Parent {
    @Id
    @GeneratedValue
    private long id;

    @OneToMany
    private Set<Child> children;
}

public class Child {
   @Id
   @GeneratedValue
   private long id;
   private String name;
}

How do you specify a one-to-many bidirectional relationship with Hibernate?

Example below shows how to make the one to many relationship bidirectional. In addition to the uni-directional @OneToMany annotation, we need to specify @ManyToOne annotation for the parent attribute in Child class.

public class Parent {
    @Id
    @GeneratedValue
    private long id;

    @OneToMany
    private Set<Child> children;
}

public class Child {
   @Id
   @GeneratedValue
   private long id;
   private String name;
   
   @ManyToOne
   private Parent parent;
}

How do you implement pagination with Hibernate?

We can specify the First Result and the Maximum No of Rows that needs to be returned from a query.

Query q = sess.createQuery("Some HQL Query");
q.setFirstResult(50); //50th row would be the first result returned
q.setMaxResults(100); //100 is the maximum number of rows returned
List cats = q.list();

What is a lazy association?

Let’s consider a Parent table associated with a corresponding Child table. When we load the Parent table, should we load the content of the Child relationship? In lazy association, the Child relationship is loaded when its need. This is the default configuration in Hibernate.

What is N + 1 selects Problem in hibernate?

Default join in hibernate is select join. In a Parent – Child relationship using select join - if a Parent has N childs – Hibernate should execute N + 1 queries to retrieve all the details of Parent and all Child’s. This is called N + 1 selects problem in Hibernate.

This can be avoided by making fetch type as join.

<set name="permissions" fetch="join">

How can you do automatic schema generation from Hibernate Mappings?

SQL DDL can be generated from mapping files by using SchemaExport tool that Hibernate Provides. We need to make sure that the mapping files provide detailed constraints like not null, maximum length, unique keys, foreign keys so that the generated schema generated has appropriate relationships and constraints. Command used to run SchemaExport is :

java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaExport options mapping_files

SchemaExport has the feature to generate incremental updates as well. Be careful when you use it, as SchemaExport depends on JDBC metadata API.

What is the use of SchemaValidator?

SchemaValidator tool can be used to verify if the mapping configured “matches” the existing database structure.

Suggest some Hibernate Best Practices?

  • Identify natural keys : Identify natural keys for all entities, and map them using .
  • Place each class mapping in its own file.
  • Externalize query strings to make applications more portable.
  • Use bind variables to prevent SQL Injection.
  • Use hand-coded JDBC sparing: Using SQL defeats the entire purpose of using Hibernate. So, use it sparingly, only when it is performance-critical.
  • Prefer lazy fetching for associations. Explicitly disable eager fetching using lazy="false". When join fetching is appropriate to a particular use case, use a query with a left join fetch.
  • Use bidirectional associations: In a large application, almost all associations must be navigable in both directions in queries.

If you loved these Questions, you will love our PDF Interview Guide with 400+ Questions.
Download it now!.

400+ Interview Questions in 4 Categories:
  1. Java : Core Java, Advanced Java, Generics, Exception Handling, Serialization, Threads, Synchronization, Java New Features
  2. Frameworks : Spring, Spring MVC, Struts, Hibernate
  3. Design : Design, Design Patterns, Code Review
  4. Architecture : Architecture, Performance & Load Testing, Web Services, REST Web Services,Security, Continuous Integration