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, save(). update(). saveOrUpdate(). saveOrUpdateCopy(). merge(). and persist(). The purpose of these methods is as follows. save method persists an entity. It assigns an identifier if entity doesn't...

Read full answer

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

Read full answer

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.

Read full answer

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

Read full answer

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

Read full answer

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.

Read full answer

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.

Read full answer

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

Read full answer

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

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

Read full answer

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

The latest version of hibernate 5.2 released on August 2016.

Read full answer

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

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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

Read full answer

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.

Read full answer

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.

Read full answer

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

Read full answer

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

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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

Read full answer

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.

Read full answer

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.

Read full answer

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

Read full answer

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.

Read full answer

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

Read full answer

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

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

40. What is the use of SchemaValidator in hibernate?

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

Read full answer

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.

Read full answer

42. What is CRUD?

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

Read full answer

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.

Read full answer

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);

Read full answer

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.

Read full answer

46. Define persistent classes in hibernate.

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

Read full answer

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.

Read full answer

48. Hibernate: Is HQL query case sensitive?

Yes. It is.

Read full answer

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

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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

Read full answer

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

Read full answer

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.

Read full answer

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

Read full answer

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.

Read full answer

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.

Read full answer

60. Explain Hibernate Disjunction.

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

Read full answer

61. What is Hibernate Conjunction?

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

Read full answer

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);

Read full answer

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

Read full answer

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);

Read full answer

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);

Read full answer

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

Read full answer

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.

Read full answer

«
»

Comments & Discussions