Prev Next

Hibernate / Hibernate interview questions II

1. Explain save, persist, saveOrUpdate and other object save methods in Hibernate. 2. Refreshing Entity objects using refresh() Method in Hibernate. 3. What is the advantage of using session.lock() in hibernate? 4. Difference between sorted and ordered collection in hibernate. 5. How do I map a composite key in Hibernate? 6. List out the design patterns used in Hibernate framework. 7. Why hibernate is preferred to use than JDBC for database interaction in various Java applications? 8. What is difference between openSession and getCurrentSession? 9. Difference between persistence.xml and hibernate.cfg.xml. 10. What is the latest version of Hibernate in use? 11. What are the best practices for defining your Hibernate persistent classes? 12. How do I implement Joins in Hibernate? 13. Explain Component mapping in hibernate. 14. Hibernate: Can we perform collection mapping with One-to-One and Many-to-One? 15. How do I create an immutable class in hibernate? 16. Hibernate: Can we switch to different relational database without any code changes? 17. How do I implement JPA for No-SQL database like mongoDB? 18. What happens when Hibernate Entity bean has no no-args constructor? 19. How do I lookup application server JNDI DataSource using Hibernate? 20. How do I reattach any detached objects in Hibernate? 21. Explain attribute oriented programming in Hibernate. 22. Does hibernate support polymorphism? 23. What are derived properties in hibernate? 24. Use of QBC API in Hibernate. 25. What do you mean by ORM metadata in hibernate. 26. Difference between managed and hibernate associations. 27. Explain HibernateTemplate. 28. List the four ORM levels in hibernate. 29. Explain pure relational ORM. 30. Explain light object mapping level of ORM. 31. What is the use of version property in hibernate? 32. Explain medium object mapping in hibernate. 33. Hibernate: What is meant by full object mapping? 34. What do you mean by Extension interfaces in hibernate? 35. How do I persist an image/media in oracle using hibernate ? 36. What is the role of JMX in hibernate? 37. How objects can be identified in Hibernate? 38. What is the use of version property in hibernate? 39. What is a lazy association in hibernate? 40. What is the use of SchemaValidator in hibernate? 41. What are the benefits of detached objects in hibernate? 42. What is CRUD? 43. What are Scalar queries in Hibernate? 44. What are entity query in hibernate? 45. Hibernate: How do you add a criteria to a query? 46. Define persistent classes in hibernate. 47. Why do we batch processing in hibernate? 48. Hibernate: Is HQL query case sensitive? 49. Explain the role of Configurationclass in Hibernate ? 50. How to prevent concurrent update in Hibernate? 51. Hibernate: disadvantages of using HQL ? 52. Hibernate:advantages of using HQL. 53. Explain flush() method in Hibernate. 54. Hibernate: Difference commit() vs flush(). 55. Explain Hibernate named query. 56. What does <![CDATA[]]> in XML mean? 57. Explain SQL Dialect in Hibernate. 58. What is hibernate proxy? 59. Explain hibernate interceptors. 60. Explain Hibernate Disjunction. 61. What is Hibernate Conjunction? 62. Explain addScalar method in Hibernate. 63. How hibernate session is related to the JDBC connection? 64. What is Hibernate Criteria Transformer? 65. How to prevent SQL Injection in hibernate? 66. How do I print a query with parameter values when using Hibernate? 67. How do we minimize the number of DB write action in Hibernate?
Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. Explain save, persist, saveOrUpdate and other object save methods in Hibernate.

Hibernate provides a handful of methods that store or update the object into the database. They are,

  1. save().
  2. update().
  3. saveOrUpdate().
  4. saveOrUpdateCopy().
  5. merge().
  6. and persist().

The purpose of these methods is as follows.

save method persists an entity. It assigns an identifier if entity doesn't exist in the database. If exists, save method performs an update. In both cases save method returns the generated ID of the entity.

Update method updates the existing object using identifier. If the identifier does not exist, it throws an exception.

saveOrUpdate method checks if the object is transient (i.e. it has no identifier) and if so it performs save that will make it persistent by generating an identifier and assigning it to session. If the object has an identifier already, it performs update().

saveOrUpdateCopy method is deprecated and no longer in use. Use merge method instead.

merge method is used to update the object to the database in any state of the session.

persist method makes a transient object persistent. However, it doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, thats why the method does not return generated ID.

2. Refreshing Entity objects using refresh() Method in Hibernate.

Sometimes, it is required to re-load an object and its collections at a time when the application database is modified with some external application or database triggers and thus corresponding hibernate entity in your becomes out of sync with its database representation.

In this case, one can use session.refresh() method to re-populate the entity with latest data available in database.

3. What is the advantage of using session.lock() in hibernate?

session.lock() method is used to reattach an object which has been detached earlier.

Using session.lock() does not check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.

4. Difference between sorted and ordered collection in hibernate.

Sorted collection is the way of sorting a collection by leveraging the sorting features provided by the Java collections framework. This sorting uses Java comparator and it takes place in the memory of JVM in which Hibernate is running, once the data being read from database.

Ordered collection refers to the sorting of a collection by specifying the order-by clause when retrieval.

Ordered collection is preferred for larger data set whereas if the collection is considerably small, sorted collection is preferred. Smaller the collection lesser impact on the JVM memory.

5. How do I map a composite key in Hibernate?

The EmbeddedId and IdClass annotations are used to denote composite primary keys.

The following are some of the rules that is applied for composite primary keys.

  • The primary key class must be public and must have a public no-arg constructor.
  • The primary key class must be serializable.
  • The primary key class must define equals and hashCode methods.

Using EmbeddedId.

@Embeddable
public class EntityKey implements Serializable {
    protected Integer compositeKey1;
    protected Integer compositeKey2;

    public EntityKey() {}

    public EntityKey(Integer key1, Integer key2) {
        this.compositeKey1 = key1;
        this.compositeKey2 = key2;
    }
    // equals, hashCode
}

@Entity
public class HibernateEntity implements Serializable {
    @EmbeddedId
    private EntityKey primaryKey;

    private String description;
    
    //...
}

Using IdClass.

  public class EntityKey implements Serializable {
  protected Integer compositeKey1;
  protected Integer compositeKey2;

  public EntityKey() {}

  public EntityKey(Integer key1, Integer key2) {
      this.compositeKey1 = key1;
      this.compositeKey2 = key2;
  }
  // equals, hashCode
}

@Entity
@IdClass(EntityKey.class)
public class HibernateEntity implements Serializable {
	@Id
	private Integer compositeKey1;
	@Id
	private Integer compositeKey2;

  private String description;
  
  //...
}

6. List out the design patterns used in Hibernate framework.
  • Domain Model Pattern - An object model of the domain that incorporates both behavior and data,
  • Data Access Object (DAO) Design Pattern,
  • Abstract Factory,
  • Data Mapper,
  • Proxy for lazy loading,
  • Object-Relational Mapping (ORM),
  • Query Object for Criterion API,
  • and facade.
7. Why hibernate is preferred to use than JDBC for database interaction in various Java applications?

Hibernate provides an Object oriented view of the database by mapping the various classes to the database tables. This facilitates Object oriented thinking rather than relational and hence increases productivity.

8. What is difference between openSession and getCurrentSession?

Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. Since this session object belongs to the hibernate context, we don't need to close it. Once the session factory is closed, this session object gets closed.To enable this feature, we need to configure it in hibernate configuration file.

<property name="hibernate.current_session_context_class">thread</property>

Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.

9. Difference between persistence.xml and hibernate.cfg.xml.

JPA leverages metadata from persistence.xml while Hibernate API uses hibernate.cfg.xml.

10. What is the latest version of Hibernate in use?

The latest version of hibernate 5.2 released on August 2016.

11. What are the best practices for defining your Hibernate persistent classes?

The persistent class cannot be final.

You must have a default no-argument constructor for your persistent classes.

getXXX() (getters) and setXXX(mutator/setter) methods for all your persistable instance variables should be available.

You should implement the equals() and hashCode() methods based on your business key.

It is recommended to implement the Serializable interface.

12. How do I implement Joins in Hibernate?

There are several ways to implement joins in hibernate.

  • By using associations such as one-to-one, one-to-many mappings.
  • Using JOIN in the HQL query. There is another form 'join fetch' to load associated data simultaneously and it is no lazy loading.
  • execute native sql query and use join keyword.
13. Explain Component mapping in hibernate.

A Component mapping is a mapping for a class having a reference to another class as a member variable.

14. Hibernate: Can we perform collection mapping with One-to-One and Many-to-One?

No. In Hibernate, collection mapping can only be performed with One-to-Many and Many-to-Many relationship.

15. How do I create an immutable class in hibernate?

Configuring the entity class property mutable to false (mutable="false"), class becomes an immutable class. By default, it is mutable="true".

16. Hibernate: Can we switch to different relational database without any code changes?

Yes. In Hibernate we can switch to different database by changing appropriate SQL Dialect configuration.

17. How do I implement JPA for No-SQL database like mongoDB?

Hibernate OGM provides Java Persistence (JPA) support for NoSQL solutions. It reuses Hibernate ORM's engine however it persists entities into a NoSQL datastore like mongoDB rather than a relational database like mySQL, Oracle etc.

18. What happens when Hibernate Entity bean has no no-args constructor?

Hibernate will fail to instantiate the entity bean and issues HibernateException.

Hibernate uses Reflection API Class.newInstance() to create instance of Entity beans that requires requires no-args constructor, usually when you call get() or load() methods. The instance of the entity bean cannot be created when there is no no-arg (default) constructor.

19. How do I lookup application server JNDI DataSource using Hibernate?

For web applications, it is always a good practice to allow servlet container to manage the connection pool. This is the reason we define JNDI resource for DataSource and we look it up in the web application. Hibernate need to used the below property to configure and lookup by JNDI DataSource name.

<property name="hibernate.connection.datasource">java:comp/env/jdbc/myTestDB</property>
20. How do I reattach any detached objects in Hibernate?

Using session.merge() method. Objects that are detached and are no longer associated with any persistent entities can be reattached by calling session.merge() method.

21. Explain attribute oriented programming in Hibernate.

In Attribute oriented programming, one can add Meta data or attributes in the source code to signify the code. For hibernate, attribute oriented programming is enabled by an engine called XDoclet.

22. Does hibernate support polymorphism?

Yes, hibernate provides complete support to polymorphism. Polymorphism queries and associations are supported at all the mapping strategies of hibernate.

23. What are derived properties in hibernate?

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

transient annotation is used to denote such properties.

24. Use of QBC API in Hibernate.

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

25. What do you mean by ORM metadata in hibernate.

All the mapping between entity class and database table, properties and columns, Java types and SQL types etc is referred as ORM metadata.

26. Difference between managed and hibernate associations.

Managed associations corresponds to the container managed persistence and it is bi-directional while hibernate associations are unidirectional.

27. Explain HibernateTemplate.

HibernateTemplate is a helper utility class that provides different methods for querying/retrieving data from the database. It also converts checked Hibernate Exceptions to unchecked DataAccessExceptions.

It manages the session and transactions by automatically opening and closing when you execute the code.

28. List the four ORM levels in hibernate.

Following are the four ORM levels in hibernate.

  • Pure Relational.
  • Light Object Mapping.
  • Medium Object Mapping.
  • and Full Object Mapping.
29. Explain pure relational ORM.

The entire application along with the user interface (UI) is designed on the basis of relational model and SQL-based relational operations.

30. Explain light object mapping level of ORM.

The entities are represented as Java classes that are mapped manually to the relational tables. The code is abstracted/hidden from the business logic using specific design patterns.

This approach is desirable for applications with less number of entities, or applications with common, metadata-driven data models.

31. What is the use of version property in hibernate?

Version property in hibernate helps to identify whether an object is in transient state or in detached state.

32. Explain medium object mapping in hibernate.

The application is built on the basis of an object model. The SQL code is generated at build time. 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.

33. Hibernate: What is meant by full object mapping?

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.

34. What do you mean by Extension interfaces in hibernate?

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 referred as Extension interfaces.

35. How do I persist an image/media in oracle using hibernate ?

Create a database table with column having data type as blob ( or equivalent) and in the HBM configuration file, specify the column type as binary.

36. What is the role of JMX in hibernate?

JMX API, a standard API manages applications and components in hibernate. JMX provides tools for development of efficient and robust distributed, web based solutions.

37. How objects can be identified in Hibernate?

Object identification can be done in hibernate in following 3 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.
38. What is the use of version property in hibernate?

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

39. What is a lazy association in hibernate?

Consider a Parent table associated with a Child table. When we load the Parent table, In lazy association, the Child relationship is loaded when it is needed. This is the default configuration in Hibernate.

40. What is the use of SchemaValidator in hibernate?

SchemaValidator tool is used to verify if the mapping configured matches the existing database structure.

41. What are the benefits of detached objects in hibernate?

Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

42. What is CRUD?

A CRUD operation deals with creating, retriving , updating and deleting from the table.

43. What are Scalar queries in Hibernate?

SQL queries that gets a list of scalars (values) is referred as scalar queries.

sess.createSQLQuery("SELECT * FROM Emp").list();

These will return a List of Object arrays (Object[]) with scalar values for each column in the Emp table.

44. What are entity query in hibernate?

Entity query gets entity objects from a native sql query using addEntity().

sess.createSQLQuery("SELECT * FROM Emp").addEntity(Employee.class);

45. Hibernate: How do you add a criteria to a query?

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

46. Define persistent classes in hibernate.

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

47. Why do we batch processing in hibernate?

Batch processing helps performing data load operations involving high volume transactions that minimize the time required and also is memory efficient.

48. Hibernate: Is HQL query case sensitive?

Yes. It is.

49. Explain the role of Configurationclass in Hibernate ?

The org.hibernate.cfg.Configuration is used to build an immutable org.hibernate. SessionFactoryobject . Configuration class object activates hibernate software and configure () is the factory method of hibernate.cfg.Configuration class which reads configuration properties from hibernate.cfg.xml file. builtSessionFactory() method uses hibernate.cfg.xml properties of Configuration object Creates jdbc connection pool.

50. How to prevent concurrent update in Hibernate?

Using Automatic Versioning Hibernate can perform automatic optimistic concurrency control. It can automatically detect if a concurrent modification occurred during user think time.

51. Hibernate: disadvantages of using HQL ?

HQL queries cannot perform DDL operations.

HQL queries cannot insert single record into table.

An HQL query gives negligible performance degradation because of conversions when compared to SQL.

HQL queries cannot call PL/SQL program.

52. Hibernate:advantages of using HQL.

HQL queries are database independent.

HQL queries are object level queries and it returns hibernate pojo class objects as results.

HQL queries and keywords are very much similar to SQL queries.

HQL queries support operators, expressions, conditions ,joins, sub queries, aggregate functions etc.

53. Explain flush() method in Hibernate.

Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you,

  • before query executions,
  • when a transaction is committed.
54. Hibernate: Difference commit() vs flush().

flush(): Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.it will update or insert into your tables in the running transaction, but it may not commit those changes.

Commit(): Commit will make the database commit.When you have a persisted object and you change a value on it, it becomes dirty and hibernate needs to flush these changes to your persistence layer.So You should commit but it also ends the unit of work.

55. Explain Hibernate named query.

Hibernate named queries lets developer to put all HQL into the XML mapping file or via annotation so that it is easy to maintain and separated from Java code.

The named query is supported in both HQL or native SQL.

The queries can be retrieved using the query names as shown below.

Query query = session.getNamedQuery("HQL_GET_ALL_EMPLOYEE");

56. What does <![CDATA[]]> in XML mean?

CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup, but should not be.

57. Explain SQL Dialect in Hibernate.

Hibernate is database agnostic and it can work with different databases. However, databases have native SQL variations, and its own set of SQL standard implementations. Therefore at some point hibernate has to use database specific SQL. Hibernate uses "dialect" configuration to know which database you are using so that it can switch to the database specific SQL generator code wherever/whenever necessary.

58. What is hibernate proxy?

The proxy attribute facilitates the lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

59. Explain hibernate interceptors.

Hibernate interceptor is a powerful feature that allows application to react to certain events that occur inside Hibernate. This allows for the implementation of generic functionality and the extension of Hibernate functionality.

60. Explain Hibernate Disjunction.

Hibernate Disjunction adds multiple restrictions/coditions to the HQL query joined by "OR" condition.

61. What is Hibernate Conjunction?

Hibernate Conjunction adds multiple restrictions/coditions to the HQL query joined by "AND" condition.

62. Explain addScalar method in Hibernate.

addScalar method specifies the result of the query to return objects for individual named columns, rather than entities.

Query myQuery = new SqlQuery("Select name as nm from employee");
myQuery.addScalar("nm", String);
63. How hibernate session is related to the JDBC connection?

A hibernate Session is similar to establishing a JDBC connection to the database. When a Session is created in Hibernate, it open up a JDBC connection to the database. When the session is clouded, its close the JDBC connection. Similarly, when transaction is started on hibernate session, it actually start a JDBC transaction.

64. What is Hibernate Criteria Transformer?

Hibernate Criteria Transformer is an interface that transforms any result of Hibernate Criteria element.

Criteria criteria = session.createCriteria(Employee.class);
	criteria.add(Restrictions.eq("name", "Jeff"));
	criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);	
65. How to prevent SQL Injection in hibernate?

Use named parameters in queries to avoid sql injection.

Query query= sessionFactory.getCurrentSession().createQuery("from UserInfo where userName=:userName");
 query.setParameter("username", userName);
66. How do I print a query with parameter values when using Hibernate?

Enable logging for the categories, org.hibernate.SQL and org.hibernate.type.

# logs SQL statements
log4j.logger.org.hibernate.SQL=debug 

# Logs JDBC parameters passed to a query
log4j.logger.org.hibernate.type=trace 

The property 'org.hibernate.SQL' is equivalent to hibernate.show_sql=true, and the second prints the bound parameters.

67. How do we minimize the number of DB write action in Hibernate?

Hibernate provides dirty checking feature that reduces database write times. Dirty checking feature updates only those fields which require a change while keeps others unchanged.

«
»
Hibernate Interview Questions III

Comments & Discussions