Latest Questions
Post Top Ad
Your Ad Spot
Friday, June 21, 2019

50 Top Hibernate Interview Questions and Answers {Updated}

Hibernate Interview Questions and Answers for experienced PDF, Read commonly asked Hibernate Job Interview Questions with Answers PDF for Freshers.


Read Hibernate Interview Questions and Answers

What is Hibernate?
Hibernate is a powerful, high-performance object/relational persistence and query service.
This lets the users develop persistent classes following object-oriented principles such as association, inheritance, polymorphism, composition, and collections.

What is ORM?
ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application into the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

What does an ORM solution comprise of?
• It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes
• Should have a language or an API for specifying queries that refer to the classes and the properties of classes
• An ability for specifying mapping metadata
• It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization
functions

What are the different levels of ORM quality?
There are four levels defined for ORM quality.
i. Pure relational
ii. Light object mapping
iii. Medium object mapping
iv. Full object mapping

What is a pure relational ORM?
The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

What is meant by light object mapping?
The entities are represented as classes that are mapped manually to the relational tables.
The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

What is meant by medium object mapping?
The application is designed around an object model. The SQL code is generated at build time. And 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. Used when the mapping exceeds 25 different database products at a time.

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.

What are the benefits of ORM and Hibernate?
There are many benefits from these. Out of which the following are the most important one.
i. Productivity – Hibernate reduces the burden of the developer by providing much of the functionality and let the developer concentrate on business logic.
ii. Maintainability – As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence, it even reduces the LOC.
iii. Performance – Hand-coded persistence provided greater performance than an automated one. But this is not true all the times. But in hibernate, it provides more
optimization that works all the time thereby increasing the performance. If it is automated persistence then it still increases the performance.
iv. Vendor independence – Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross-platform application.

How does the hibernate code looks like?
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass (“Sample App”);
session.save(mpc);
tx.commit();
session.close();
The Session and Transaction are the interfaces provided by hibernate. There are many other interfaces besides this.

What is a hibernate XML mapping document and how does it look like?
In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes’ map to the columns of the relative tables in database.
<?xml version=”1.0″?> <!DOCTYPE hibernate-mapping PUBLIC
<“http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd”>
<hibernate-mapping>
<class name=”sample.MyPersistanceClass” table=”MyPersitaceTable”>
<id name=”id” column=”MyPerId”> <generator class=”increment”/>
</id>
<property name=”text” column=”Persistance_message”/>
<many-to-one name=”nxtPer” cascade=”all” column=”NxtPerId”/>
</class>
</hibernate-mapping>
Everything should be included under <hibernate-mapping> tag. This is the main tag for an xml mapping document.

Explain the general flow of Hibernate communication with RDBMS
The general flow of Hibernate communication with RDBMS is :
• The Hibernate configuration is to be loaded and the creation of configuration object is done. The mapping of all hbm files will be performed automatically.
• Creation of a session factory from the configuration object.
• Obtain a session from the session factory.
• Creation of HQL Query
• Execution of the query in order to get the list of containing java objects.

What the Core interfaces are of hibernate framework?
There are many benefits from these. Out of which the following are the most important one.
i. Session Interface – This is the primary interface used by hibernate applications.
The instances of this interface are lightweight and are inexpensive to create and destroy.
Hibernate sessions are not thread safe.
ii. SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally, there will be a single SessionFactory for the whole application and it will be shared among all the application threads.
iii. Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
iv. Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
v. Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.

What are the Callback interfaces?
These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.

What are Extension interfaces?
When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that the user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.

What are the Extension interfaces that are there in hibernate?
There are many extension interfaces provided by hibernate.
ProxyFactory interface – used to create proxies
ConnectionProvider interface – used for JDBC connection management
TransactionFactory interface – Used for transaction management
Transaction interface – Used for transaction management
TransactionManagementLookup interface – Used in transaction management.
Cache interface – provides caching techniques and strategies
CacheProvider interface – same as Cache interface
ClassPersister interface – provides ORM strategies
IdentifierGenerator interface – used for primary key generation
Dialect abstract class – provides SQL support

What are different environments to configure hibernate?
There are mainly two types of environments in which the configuration of the hibernate application differs.
i. Managed environment – In this kind of environment, everything from database connections, transaction boundaries, security levels and all are defined. An example of
this kind of environment is environment provided by application servers such as JBoss,
Weblogic and WebSphere. ii. Non-managed environment – This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.

What is the file extension you use for hibernate mapping file?
The name of the file should be like this: filename.hbm.xml
The filename varies here. The extension of these files should be “.hbm.xml”.
This is just a convention and it’s not mandatory. But this is the best practice to follow this extension.

What do you create a SessionFactory?
Configuration cfg = new Configuration();
cfg.addResource(“myinstance/MyConfig.hbm.xml”);
cfg.setProperties( System.getProperties() );
SessionFactory sessions = cfg.buildSessionFactory();
First, we need to create an instance of Configuration and use that instance to refer to the location of the configuration file. After configuring this instance is used to create the SessionFactory by calling the method buildSessionFactory().

What is meant by Method chaining?
Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to the actual java code. And it is not
mandatory to use this format. Look how a SessionFactory is created when we use method chaining.
SessionFactory sessions = new Configuration()
.addResource(“myinstance/MyConfig.hbm.xml”)
.setProperties( System.getProperties() )
.buildSessionFactory();

What does hibernate properties file consist of?
This is a property file that should be placed in application class path. So when the Configuration object is created, hibernate is first initialized. At this moment the application will automatically detect and read this hibernate.properties file.
hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB
hibernate.transaction.factory_class =
net.sf.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class =
net.sf.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect

What should SessionFactory be placed so that it can be easily accessed?
As far as it is compared to the J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various
components that hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file.

What are POJOs?
POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather than simple java classes.

What is object/relational mapping metadata?
ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations.

What is HQL?
HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.

What are the different types of property and class mappings?
• Typical and most common property mapping
<property name=”description” column=”DESCRIPTION” type=”string”/>
Or
<property name=”description” type=”string”>
<column name=”DESCRIPTION”/>
</property>
• Derived properties
<property name=”averageBidAmount” formula=”( select AVG(b.AMOUNT) from BID b
where b.ITEM_ID = ITEM_ID )” type=”big_decimal”/>
• Typical and most common property mapping
<property name=”description” column=”DESCRIPTION” type=”string”/>
• Controlling inserts and updates
<property name=”name” column=”NAME” type=”string”
insert=”false” update=”false”/>

What is Attribute Oriented Programming?
XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses the Javadoc tag format (@attribute) to specify class-, field-, or method-level metadata attributes. These attributes are used to generate hibernate mapping file automatically when the application is built. This kind of programming that works on attributes is called Attribute Oriented Programming.

What are the different methods of identifying an object?
There are three methods by which an object can be identified.
i. Object identity –Objects are identical if they reside in the same memory location in the JVM. This can be checked by using the = = operator.
ii. Object equality – Objects are equal if they have the same value, as defined by the equals( ) method. Classes that don’t explicitly override this method inherit the
implementation defined by java.lang.Object, which compares object identity.
iii. Database identity – Objects stored in a relational database are identical if they represent the same row or, equivalently, share the same table and primary key value.

What are the different approaches to represent an inheritance hierarchy?
i. Table per concrete class.
ii. Table per class hierarchy.
iii. Table per subclass.

What are managed associations and hibernate associations?
Associations that are related to container management persistence are called managed associations. These are bi-directional associations. Coming to hibernate associations, these are unidirectional.

Why do you need an ORM tool like Hibernate?
ORM tools like hibernate provide the following benefits:
• Improved performance: Lazy loading, Sophisticated caching, Eager loading
• Improved productivity: High-level object-oriented API, Less Java code to write, No SQL to write
• Improved maintainability: A lot less code to write
• Improved portability: ORM framework generates database-specific SQL for you

What are the main advantages of ORM like hibernate?
Hibernate implements extremely high-concurrency architecture with no resource-contention issues. This architecture scales extremely well as concurrency increases in a cluster or on a single machine.
Another performance related optimizations that hibernate performs are:
• Caching objects
• Executing SQL statements later, when needed
• Never updating unmodified objects
• Efficient Collection Handling
• Rolling two updates into one
• Updating only the modified columns
• Outer join fetching
• Lazy collection initialization
• Lazy object initialization

What are the core interfaces of Hibernate framework?
1. Session Interface: The basic interface for all hibernate applications. The instances are light weighted and can be created and destroyed without an expensive process.
2. SessionFactory interface: The delivery of session objects to hibernate applications is done by this interface. For the whole application, there will be generally one SessionFactory and can be shared by all the application threads.
3. Configuration Interface: Hibernate bootstrap action is configured by this interface. The location specification is specified by specific mapping documents, is done by the instance of this interface.
4. Transaction Interface: This is an optional interface. This interface is used to abstract the code from a transaction that is implemented such as a JDBC / JTA transaction.
5. Query and Criteria interface: The queries from the user are allowed by this interface apart from controlling the flow of the query execution.

Explain how to configure Hibernate?
Answer: 1
Hibernate uses a file by name hibernate.cfg.xml. This file creates the connection pool and establishes the required environment. A file named .hbm.xml is used to author mappings. The bootstrap action is configured by using the Configuration interface.
There are two types of environment to configure hibernate:
1. Managed Environment: The definitions of database operations such as connections, transaction boundaries, security levels. This environment is provided by application servers such as JBoss, Weblogic, Websphere.
2. Non-managed Environment: The basic configuration template is provided by this interface. Tomcat is one of the examples that best support this environment.
Answer: 2
Programmatic configuration
The org.hibernate.cfg.Configuration instance can be instantiated directly by specifying XML mapping documents. If the mapping files are in the classpath, use addResource().
Configuration cfg = new Configuration()
.addResource(“Item.hbm.xml”)
.addResource(“Bid.hbm.xml”);
An alternative way is to specify the mapped class and allow Hibernate to find the mapping document:
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);
org.hibernate.cfg.Configuration also allows you to specify configuration properties:
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class)
.setProperty(“hibernate.dialect”, “org.hibernate.dialect.MySQLInnoDBDialect”)
.setProperty(“hibernate.connection.datasource”, “java:comp/env/jdbc/test”)
.setProperty(“hibernate.order_updates”, “true”);
Alternative options include:
Passing an instance of java.util.Properties to Configuration.setProperties().
Placing a file named hibernate.properties in a root directory of the classpath.
Setting System properties using java -Dproperty=value.
Including elements in hibernate.cfg.xml (this is discussed later).
Hibernate JDBC Properties:
hibernate.connection.driver_class
hibernate.connection.url
hibernate.connection.username
hibernate.connection.password
hibernate.connection.pool_size

What is a HibernateTemplate?
HibernateTemplate is a helper class that is used to simplify the data access code. This class supports automatically converts HibernateExceptions which is a checked exception into DataAccessExceptions which is an unchecked exception. HibernateTemplate is typically used to implement data access or business logic services. The central method is execute(), that supports the Hibernate code that implements the HibernateCallback interface.

What are the benefits of HibernateTemplate?
The benefits of HibernateTemplate are:
• HibernateTemplate, which is a Spring Template class, can simplify the interactions with Hibernate Sessions.
• Various common functions are simplified into a single method invocations.
• The sessions of hibernate are closed automatically
• The exceptions will be caught automatically and convert them into runtime exceptions.

What is Hibernate proxy?
Mapping of classes can be made into a proxy instead of a table. A proxy is returned when actually a load is called on a session. The proxy contains the actual method to load the data. The proxy is created by default by Hibernate, for mapping a class to a file. The code to invoke JDBC is contained in this class.
Explain the types of Hibernate instance states.
The persistent class’s instance can be in any one of the three different states. These states are defined with a persistence context. The Hibernate has the following instance states:
• Transient: This instance is never been associated with any one of the persistence processes. This does not have a persistent identity like primary key value.
• Persistent: A persistent context is made to associate with the current instance. It has a persistent identity like primary key value and a corresponding row of a table in the database. Hibernate guarantees the persistent identity is equivalent to the java Identity [object], for a particular persistence context
• Detached: This instance associated with a persistence context is only once and the context was closed or serialized to another process. The persistent identity is retained and it can be a corresponding row in a database.

What are Collection types in Hibernate?
• ArrayType,
Constructor: ArrayType(String role, String propertyRef, Class elementClass, boolean isEmbeddedInXML)
• BagType,
Constructor: BagType(String role, String propertyRef, boolean isEmbeddedInXML)
• CustomCollectionType, A custom type for mapping user-written classes that implement PersistentCollection
Constructor: CustomCollectionType(Class userTypeClass, String role, String foreignKeyPropertyName, boolean isEmbeddedInXML)
• IdentifierBagType,
Constructor: IdentifierBagType(String role, String propertyRef, boolean isEmbeddedInXML)
• ListType,
Constructor: ListType(String role, String propertyRef, boolean isEmbeddedInXML)
• MapType,
Constructor: MapType(String role, String propertyRef, boolean isEmbeddedInXML)
• SetType
Constructor: SetType(String role, String propertyRef, boolean isEmbeddedInXML)

What is lazy initialization in hibernate?
The delaying the object creation or calculating a value or some process until the first time it is needed. The retrieval of particular information only at the time when the object is accessed, is lazy initialization in hibernate. A scenario for lazy initialization is:
When the field creation is expensive, a field may or may not be invoked.
In this scenario, the creation of a field can be deferred until the actual moment is arise to use it. The performance is increased using this technique, by avoiding unnecessary creation of objects which is expensive and consumes the memory space.

What is lazy fetching in hibernate?
• Lazy setting decides whether to load child objects while loading the Parent Object.
• This can be done by a setting in the hibernate mapping file of the parent class.Lazy = true
• By default the lazy loading of the child objects is true.

What is the difference between sorted and ordered collection in hibernate?
Sorted Collection:
The sorted collection is a collection that is sorted using the Java collections framework. The sorting is done in the memory of JVM that is running hibernate, soon after reading the data from the database using Java Comparator The less the collection the more the efficient of sorting
Ordered Collection:
The order collections will also sort a collection by using the order by clause for the results fetched.
The more the collection, the more efficient of sorting.

Explain the advantages and disadvantages of detached objects
Advantages:
• Detached objects passing can be done across layers up to the presentation layer without using Data Transfer Objects.
• At the time of using long transactions by the user which needs long think-time, it is suggested to split these transactions into some transactions. The detached objects get modified apart from the transaction scope which then can be re-attached to a new transaction.
Disadvantages:
• The usage of detached objects is cumbersome and cryptic. It is suggested not to be cluttered with the session, if possible.
• It is recommended to use DataTransferObjects and DomainObjects that is used to maintain separation between the user interfaces and the Service.

What is Hibernate Query Language (HQL)?
Hibernate Query Language is designed for data management using Hibernate technology. It is completely object-oriented and hence has notions like inheritance, polymorphism, and abstraction. The queries are case-sensitive. This has an exception for Java classes and properties. The query operations are through objects. HQL acts as a bridge between Objects and RDBMS.

Explain the role of Session interface in Hibernate
• In hibernate, the Session interface wraps a JDBC connection, holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier and is a factory for Transaction
• Session session = sessionFactory.openSession();
• The Session interface is the primary interface used by Hibernate applications.
• It is a single-threaded, short-lived object representing a conversation between the application and the persistent store.
• It allows you to create query objects to retrieve persistent objects.

State the role of SessionFactory interface plays in Hibernate.
• An application obtains Session instances from a SessionFactory which is typically single for the whole application created during its initialization.
• The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime.
• It also holds cached data that has been read in one unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();

What is the difference between merge and update?
update (): When the session does not contain a persistent instance with the same identifier, and if it is sure to use an update for the data persistence in hibernate.
merge (): Irrespective of the state of a session, if there is a need to save the modifications at any given time, use merge().

What is the advantage of Hibernate over JDBC?
The advantages of Hibernate over JDBC are:
• Hibernate code will work well for all databases, for ex: Oracle, MySQL, etc. whereas JDBC is database specific.
• No knowledge of SQL is needed because Hibernate is a set of objects and a table is treated as an object, whereas to work with JDBC, one need to know SQL.
• Query tuning is not required in Hibernate. The query tuning is automatic in hibernate by using criteria queries, and the result of performance is at its best. Whereas in JDBC the query tuning is to be done by the database authors.
• With the support of cache of hibernate, the data can be placed in the cache for better performance. Whereas in JDBC the java cache is to be implemented.

Why hibernate is advantageous over Entity Beans & JDBC?
An entity bean always works under the EJB container, which allows reusing of the object external to the container. An object cannot be detached in entity beans and in hibernate detached objects are supported.
Hibernate is not database dependent whereas JDBC is database dependent. Query tuning is not needed for hibernate as JDBC is needed. Data can be placed in multiple caches which is supported by hibernate, whereas in JDBC the cache is to be implemented.

Explain the main difference between Entity Beans and Hibernate
Entity beans are to be implemented by containers, classes, descriptors. Hibernate is just a tool that quickly persists the object tree to a class hierarchy in a database and without using a single SQL statement. The inheritance and polymorphism are quite simply implemented in hibernate which is out of the box of EJB and a big drawback.

Explain the difference between Hibernate and Spring.
Hibernate is an ORM tool for data persistence. Spring is a framework for enterprise applications. Spring supports hibernate and provides the different classes which are templates that contain the common code.

Post Top Ad

Your Ad Spot

Pages