Hibernate fresher interview question/Hibernate Interview Questions and Answers for Freshers & Experienced

What is Value replacement in Message Resource Bundle work?

Hibernate Validator’s ResourceBundleMessageInterpolator generates two instances of ResourceBundleLocator one for UserDefined validation Standard validation messages – defaultResourceBundleLocator.

What is One to Many Bi-directional Relation in Hibernate?

It is the Reference of the handle of the association attribute of the many views as the benefit of the mappedBy attribute, Hibernate has all the erudition it needs. With these processes, we need to define a bidirectional many-to-one association.

What is the difference between identity and increment generator in hibernate ?

Identity :
1. It is database software dependent.
2. Id field mapped column must have auto increment constraint.
3. consider deleted value while generating new id value.
4. Database software use id value after inserting record.
Increment :
1. It is database software independent.
2. Id field mapped column not required.
3. Deleted value does not consider while generating new id value.
4. Hibernate software generate id value.

Which one is the default generator in hibernate ?

Assigned Generator is the default generator if no generator is configured.

What are Generators in Hibernate?

Hibernate gives set of pre-defined algorithms as identity value generator to generate identity value for hibernate domain class object while saving them to database.

All the generator classes implements the org.hibernate.id.IdentifierGenerator interface. The application programmer may create one’s own generator classes by implementing the IdentifierGenerator interface. Hibernate framework provides many built-in generator classes:

1. assigned
2. increment
3. sequence
4. hilo
5. native
6. identity
7. seqhilo
8. uuid
9. guid
10. select
11. foreign
12. sequence-identity

What is Object Versioning and How to enable it ?

The process of keeping track of how many times, the loaded object is modified through hibernate persistance logic is known as versioning.

To implement this feature in our project we just need to add “@Version” annotation in our entity class.

Example :

@Version
@Column(name=”ver_col”)
private int version;

Which annotation is used to declare a class as a hibernate bean ?

@Entity annotation is used to declare a class as an entity.

Example

@Entity
@Table(name="posts")
public class Post{
String title;
String description;
}

What is Hibernate Query Language (HQL)?

Hibernate query language, HQL is an object-oriented extension to SQL. It allows you to query, store, update, and retrieve objects from a database without using SQL.
This question is also similar to the earlier question about Criterion query, Java developers who have not used Hibernate extensively will not know much about features like HQL and Criterion.

Difference between time to live and time to idle in Ehcache.

TimeToIdleSeconds enables cached object to be invalidated if it has not been requested for specified ('timeToIdleSeconds' ) seconds.

TimeToLiveSeconds enables cached object to be invalidated after that many seconds regardless of how many times or when cache was requested last time.

How do you find if an particular object exists at session cache?

We can use session contains() method to check if an object is present in the hibernate cache or not, if the object is found in cache, it returns true or else it returns false.

What are the different CacheMode in second level cache of hibernate?

There are 4 different CacheMode.

1. CacheMode.NORMAL : This mode allows to read and write data in second level cache.
2. CacheMode.GET : In this mode, data will be read but will not be written in second level cache.
3. CacheMode.PUT : Data will be written but not will be read from second level cache.
4. CacheMode.REFRESH : Data will be written and will not be read from second level cache. The difference between Put and Refresh is that CacheMode.

Explain shared cache mode in second level cache of Hibernate.

1. ENABLE_SELECTIVE: Entities will not be cached until entity will be annotated by cacheable.
2. DISABLE_SELECTIVE : Those entities are cached which are explicitly not annotated with cacheable.
3. ALL : Every entities will be cached.
4.NONE: No entity will be cached.

Advantages of EHCache (Easy Hibernate cache).

The below are the advantages of EHCache. (org.hibernate.cache.EhCacheProvider)

It is fast.
lightweight.
Easy-to-use.
Supports read-only and read/write caching.
Supports memory-based and disk-based caching.

Explain second level cache in hibernate.

Second level cache is on SessionFactory level. All the second level cache provider class must implement org.hibernate.cache.spi.CacheProvider by configuring the property hibernate.cache.provider_class. Hibernate provides open source cache providers also.

How can you differentiate session.save() and session.persist() method?

Session.save() it’s used for saving the object in the database and session.persist() for transient, persistent objects.

What is @Transient in Hibernate? What is the use of this?

Hibernate supports various object states. One of this object state is transient. In hibernate which is object relation mapping, it will map or create every variable with the class we have defined. For example, if we declare a new variable it will add its entry to the database. But if a variable is marked @Transient then it will not be added to the database. This means it has no persistence representation in that hibernate session. And after an application is closed these transient objects will be destroyed through garbage collection.

class Edufect{
private int id;
private String courseName;
@Transient
private int courseId;
}

So in this in our database, we can see the entry of id column, courseName but no courseId column. But if we remove transient annotation from courseId then it will be added as an int to the database.

What is the main difference between spring and hibernate?

Spring and Hibernate are two different things, Spring has several components like Dependency Injection, Spring MVC, Spring ORM, Spring Rest API. So Spring ORM and Hibernate are kind of similar, they both deal with the object relation model, which means they deal with connection java objects to database entities.

Now if you want to build a Rest API using Spring, you can use the Spring Rest API (Here is the getting start guide for Spring Rest Building a RESTful Web Service) for ORM you can either choose Hibernate or Spring ORM framework in either cases there are advantages and disadvantages but major industry goes with using Hibernate (I might be wrong!!) I’ve used both of them Spring ORM is quite useful in simple scenarios and Hibernate in some complex scenarios, whereas in most complex scenarios both of them are not quite useful when you want to write really complex queries. (Both of them provide functionalities two write queries by yourself in the case of complex scenarios).

List Data types supported in Hibernate?

Hibernate maps Java data types into databases. Java type can be mapped into one or more column in the database. We can set the Object’s record as primitive types like int, byte or more complex, for example, java.util.Currency.

Data types supported in Hibernate are
1. Primitive types.
2. Date and time types.
3. Binary and large object types.
4. Other JDK-related types.

What types of joins can you use in Hibernate?

There are multiple ways to use join in Hibernate.
1. Using relationships such as one-to-one, one-to-many or many-to-many
2. Using joins in native SQL query
3. Using joins in HQL

What are inheritance mapping strategies are available in Hibernate?

There are three strategies supported by Hibernate. You can use xml files or JPA annotation to implement them.

1. Table per Hierarchy
2. Table per concrete class
3. Table per subclass

What are two types of Collections in hibernate?

1. Sorted Collection
2. Ordered Collection

Describe the important interfaces of Hibernate framework?

Important interfaces of Hibernate framework are:

SessionFactory (org.hibernate.SessionFactory)
It is an immutable thread safe cache of compiled mappings for a single database.
We are supposed to initialize SessionFactory once and then we are allowed to cache and reuse it.
The SessionFactory instance is used to return the session objects for database operations.
Session (org.hibernate.Session)
It is a single threaded and short-lived object, which represents a conversation between the persistent store and the application.
The session should be opened only when it is required and should be closed as soon as the user is done.
The session object is the interface between hibernate framework and Java application code and it provides methods for the CRUD operations.
Transaction (org.hibernate.transaction)
It is a single threaded and short-lived object used by the application, which specifies atomic units of work.
The application is abstracted from the underlying JDBC or JTA transaction.

What is Lazy loading in hibernate ?

It is a technique in where the objects are loaded on the requirement basis. Since the Hibernate 3 version, the lazy loading is by default enabled so that the child objects are not loaded while the parent is loaded.

What are differences between save and saveOrUpdate method of session object?

save(): stores object in database. It generates identifier for tQhe object and returns it. If object already exists in database, it will throw an error.
saveOrUpdate(): SaveOrUpdate method save the object if identifies does not exist. If it exists , it calls update method.

What is HQL?

HQL stands for Hibernate query language. It is very simple, efficient and object oriented query languages which simplifies complex SQL queries. Instead of table, you use object to write queries.

Can you declare Entity class as final in hibernate?

Yes, you can declare entity class as final but it is not considered as a good practice because hibernate uses proxy pattern for lazy initialisation, If you declare it as final then hibernate won’t be able to create sub class and won’t be able to use proxy pattern, so it will limit performance and improvement options.

Explain the Criteria object in Hibernate?

Criteria objects are used to create and execute object-oriented Queries to retrieve the objects.

Mention the Key components of Hibernate?

The Key components of Hibernate are:
Session: It is used to get a physical network with a database.
Transaction: It represents the unit of work with a database.
Query: It uses SQL and HQL string to retrieve the data from the database and create objects.
Criteria: It is used to create and execute object-oriented queries and retrieve the objects.
Configuration: It represents the properties of files required by Hibernate
Session Factory: It configures hibernate for the application using the provided configuration file and instantiates the session object.

What is the difference between getting () and load() methods in Hibernate?

Getting() and load() which are used for fetching data for the assigned identifier. Get() method return null,load() method throws error of object not found type of exception.

What are the various fetching strategies available in Hibernate?

Join-Fetching and Select Fetchings are the fetchings available in Hibernate.

Is it possible to run a native SQL query in hibernate?

We can execute native SQL query in hibernate with the help of SQLQuery object. Still, We should avoid this approach because we cannot use the benefits of hibernate first-level caching and hibernate association.

What are the benefits of Hibernate Tools Eclipse plugin?

Hibernate Tools plugin helps the users in writing hibernate configuration and mapping files quickly. The primary benefit is the content assist in assisting the user with different properties and XML tags to use. It validates them against the Hibernate DTD files, so the user knows any mistakes beforehand.

Explain the process of Session object and how we can use it in a first-level cache and a second-level cache?

First level caching: It starts with each session basis, with a “session” object.

Second level caching: It can be shareable beyond multiple sessions.

How can you differentiate Entity Beans and Hibernate.

Entity beans are containers, classes, descriptors. Hibernate is a tool that instantly persists the object tree to a class.

Describe your favourite features of the Hibernate framework.

ORM Tool, Hibernate provides a powerful query language (HQL)

How to use JNDI DataSource with the Hibernate framework?

It’s always useful to allow a servlet container to manage the connection pool as the user so that we define JNDI resource for DataSource, and we can use it in the web application. It’s straightforward to use in Hibernate, all we need is to remove all the database-specific properties and use the below feature to provide the JNDI DataSource name.

Example

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

How to implement relationships in hibernate?

We can quickly implement relationships like One to One Mapping, One to Many Mapping, and Many to Many Mappingusing JPA annotations as well as XML based configurations.

What is the use of the Hibernate Session merge() call?

We can use the Hibernate Session merge() to update existing values; however, this method creates a copy from the passed entity object and returns it. The returned object is part of the persistent context and tracked for any changes; the given object is not tracked. For example, a program, read Hibernate merge.

What is a One-to-One association in Hibernate?

1. A one to one association is similar to many to one association, and only one difference is that it must be set as a unique one. We can use many to one element to define one to one association.
2. A name attribute must set in the parent class, and the column attribute is used to set a column name in the parent table for the defined variable. It is unique so that only one object gets associated with another.

What is Hibernate caching?

Query interface is object oriented representation of Hibernate Query. You can get query object bu calling Session.createQuery() method.

Here is simple example to execute Native query using Query APIs.

SQLQuery query = session.createSQLQuery("select name, age from Employee");
List<Object[]> rows = query.list();
for(Object[] row : rows){
Employee e = new Employee();
e.setName(row[0].toString());
e.setAge(Integer.parseInt(row[1].toString()));
System.out.println(e);
}

What is a Many-to-One association in Hibernate?

This association is the common type of association where one object can be associated with multiple objects.
And Many-to-one element defines the Many-to-One association.To the defined variable, a name attribute is set in the parent class and column attribute sets the column name in the parent table.

What is One-to-Many association in Hibernate?

In this association, one object can be associated with multiple objects.
The One-to-Many mapping is implemented using a Set Java collection that does not have any redundant element.
A One-to-Many element of the set element indicates the relation of one object to multiple objects.

Explain the Query object in Hibernate?

These objects use SQL and HQL string to retrieve data from the database and create objects.
An instance of Query is used to bind query parameters, restrict the number of results returned by the query and finally to execute the query.

Explain the Transaction object in Hibernate?

It represents a unit of work with the database and most of the RDBMS (Relational Database Management System) supports transaction functionality.
In Hibernate, transactions are managed by an underlying transaction manager and transaction from JDBC or JTA.
It is an optional object and the Hibernate Application do not use this interface, instead, they handle the transactions in their code.

Explain brief about SessionFactory object used in hibernate?

SessionFactory is heavy weight object and it should be created one per database. SessionFactory object is shared by multiple sessions.

Explain brief about Session interface used in hibernate?

Session interface is primarily used by hibernate application. Session is light weight,short lived objects which are inexpensive to create and destroy. It allows you to create query objects to retrieve persistent objects.It wraps JDBC connection Factory for Transaction.It holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier .

What are some core interfaces of hibernate?

1. Session
2. SessionFactory
3. Configuration
4. Transaction
5. Query and Criteria interface.

What is ORM?

ORM stands for Object Relational mapping. It is programming paradigm which is used to persist java objects to database tables.

What are the advantages of Hibernate over JDBC?

Apart from Persistence i.e. saving and loading data from Database, Hibernate also provides the following benefits

1) Caching
2) Lazy Loading
3) Relationship management and provides code for mapping an object to the data
4) The developer is free from writing code to load/store data into the database.

What is Hibernate?

Hibernate is an ORM (Object-relational Mapping) framework, which allows the developer to concentrate on business logic by taking care of the persistence of data by itself.Java developer can write code using an object and Hibernate can take care of creating those object from data loaded from the database and saving update back to the database.

Search
R4R Team
R4R provides Hibernate Freshers questions and answers (Hibernate Interview Questions and Answers) .The questions on R4R.in website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,Hibernate fresher interview question,Hibernate Freshers & Experienced Interview Questions and Answers,Hibernate Objetive choice questions and answers,Hibernate Multiple choice questions and answers,Hibernate objective, Hibernate questions , Hibernate answers,Hibernate MCQs questions and answers Java, C ,C++, ASP, ASP.net C# ,Struts ,Questions & Answer, Struts2, Ajax, Hibernate, Swing ,JSP , Servlet, J2EE ,Core Java ,Stping, VC++, HTML, DHTML, JAVASCRIPT, VB ,CSS, interview ,questions, and answers, for,experienced, and fresher R4r provides Python,General knowledge(GK),Computer,PHP,SQL,Java,JSP,Android,CSS,Hibernate,Servlets,Spring etc Interview tips for Freshers and Experienced for Hibernate fresher interview questions ,Hibernate Experienced interview questions,Hibernate fresher interview questions and answers ,Hibernate Experienced interview questions and answers,tricky Hibernate queries for interview pdf,complex Hibernate for practice with answers,Hibernate for practice with answers You can search job and get offer latters by studing r4r.in .learn in easy ways .