15.1 C
Delhi
Monday, November 25, 2024
Home > Interview TipsHibernate Interview Questions and answers for freshers

Hibernate Interview Questions and answers for freshers

Hibernate is an object-relational mapping framework that is based on a Java framework. This framework allows a software developer to map plain old Java objects to database tables. The hibernate framework relieves the developer from using the standard data persistence-related complex configurations and tasks.


This is done by mapping plain old Java objects with database tables accurately. It is also done abstractly, which is the most crucial part. The developer is not required to know the internal complications. The queries can also be executed in the same manner as the abstraction. These features help the developer save time.


Both freshers and experienced candidates require knowledge of the Hibernate framework. In addition, a good understanding of hibernate interview questions is necessary before the candidates present themselves for the interview.


Hibernate Interview questions are important to students as they are the most widely used object-relational mapping tools. However, hibernate interview questions for experienced students are most significant and play the chief role.

Here are some of the commonly asked Hibernate interview questions for freshers:

1. What is ORM in the Hibernate framework?


ORM in the Hibernate framework stands for Object Relational Mapping. ORM is a mapping tool. This is used to convert data stored in a relational database to object-oriented programming constructs. ORM helps in providing accuracy and efficiency. It also helps in simplifying the retrieval of data, creation of data and manipulation of data.

2. What is hibernate?


Hibernate is among the most famous and commonly used Java frameworks. This framework helps in simplifying the development of Java applications. It helps developers to interact with the database. It is an ORM or an Object-relational mapping tool. Hibernate framework also helps in the creation or implementation of Java API.


This framework handles the conversion and implementation of data internally. The tool provides an abstraction layer. Hence, the data is arranged abstractly. The tasks implemented by the framework are writing queries for CRUD operations and creation of connection and basis for interaction with the databases.


Hibernate creates and develops a connection that helps in the storage and processing of data for long-term usage. This tool is lightweight. It is also significant to note that the tool is open-sourced. This makes the tool favourable and makes it more lucrative than other frameworks.

3. What are the advantages of Hibernate over JDBC?


The advantages of Hibernate over JDBC are as follows:

Hibernate Query Language: Hibernate framework provides the developer with Hibernate Query Language. This language provides a closer view of Java. It is also object-oriented. This relieves some burden off the developers in writing database independent queries. On the other hand, in JDBC, a developer is required to know the database-specific codes.


Clean Readable Code: In hibernate framework, much of the JDBC API-based boiler-plate codes can be removed. This makes the code look neater and more legible and readable.


Exception Handling: Hibernate framework overtakes the JDBC exceptions and also eliminates JDBC unchecked exceptions like JDBCExceptions or HibernateException.

This framework with the built-in transaction management system provides the developers with a helping hand in avoiding the need to write multiple tri-catch blocks to handle exceptions. On the other hand, in JDBC, the framework throws a checked exception known as SQLException. This required the developer to know and write try-catch blocks which will handle the exception at the time of compiling.


Special Features: Hibernate framework also provides special features such as it supports OOP features. Features like inheritance, associations and support collections can be supported. These special features are not available in JDBC.


Transaction Management: Hibernate Framework supports implicit transaction management. Whereas, in JBC, the developer has to write transaction management code utilizing the commit and rollback methods.

4. What are the advantages of Hibernate Framework?


Here are the advantages of using Hibernate Framework:
This framework is a lightweight framework.
Hibernate is open-sourced which provides it with an upper hand over other frameworks.
The framework helps the developer is generating queries independent from the database.
A table can be automatically created with the facilities provided by Hibernate Framework.
The framework provides the developer with query statistics and database status.

5. What are the important interfaces Hibernate framework?


Some of the important core interfaces are:
Configuration
Session factory
Criteria
Query
Session
Transaction

6. Why must one use Hibernate Framework?


Here are a few reasons to use the hibernate framework:
Hibernate Framework compensates for the deficiencies of other technologies like JDBC.
JDBC faces the difficulty of database dependency. This is not the case in Hibernate Frameworks.
Hibernate framework does not require a lot of work in changing the database.
Hibernate framework provides the option of code portability. JDBC does not provide this option.
This framework helps in strengthening the object level relationship.
Hibernate framework handles the exceptions in the database. In JDBC, the developer must work on exception-handling.
This framework reduces the length of the code. It also increases the readability of the code by eliminating the boilerplate problem.

7. What is a Session core in Hibernate framework?


A session in the Hibernate framework is an object. This object helps the developer in maintaining the connection between the Java object application and database. Session object also provides ways for storing, retrieving and modifying data from the database. This is done by using methods such as persist(), load(), get(), update(), delete(), etc. In addition, the framework also has methods to return Query, Criteria and Transaction objects.

8. Name a few different functionalities supported by Hibernate.


A few functionalities supported by Hibernate are:
Hibernate is an object-relational mapping tool.
Hibernate framework uses HQL or Hibernate Query Language. This makes the framework database-independent.
This framework also supports auto DDL operations.
The Hibernate framework in Java also uses Auto Primary Key Generation support.
This framework supports cache memory.
Hibernate framework does not require developers to write code for exception handling.

9. What is the Session Factory core in the Hibernation framework?


SessionFactory provides the developer with an instance of Session. It is a factory class. It provides Session objects according to the configuration parameters. This helps in establishing a connection to the database. The framework usually has a single instance of SessionFactory. The internal state of the SessionFactory cannot be modified as it includes metadata about ORM. Once this instance is created, it cannot be changed.
This core also provides access to information such as statistics and metadata which are related to class and query executions. If enables, the framework also holds second-level cache data.

10. Name the technologies that are supported by Hibernate.


Hibernate framework supports numerous technologies such as:
Maven
Eclipse Plug-ins
XDoclet Spring
J2EE

11. State what you think about the statement “session being a thread-safe object”?


This statement is false. The session is not a thread-safe object. Here, any number of threads have access to the data from it at the same time.

12. How to achieve mapping in Hibernate?


Hibernate offers various features with association mapping being one of them. This framework supports the same associations as the relational database model. These associations can be mapped as a uni-directional or bi-directional association. These associations are as follows:
One-to-One associations
Many-to-One associations
Many-to-Many associations

13. What is lazy loading in hibernate?


Lazy load is a function that is chiefly used by developers for improving application performance. This is done by helping to load the child objects on demand. It is important to consider the fact the since the Hibernate 3 version, the lazy loading feature is enabled by default. This means that the child objects are not loaded until the parent objects get loaded.

14. What is the One-to-One association in Hibernate framework?


In One-to-one mapping, the developer is required to model the system for the entity for which they want to navigate the relationship in their query or domain model. The developer needs an entity attribute that represents the association. Hence, it must be annotated with a @OneToOne annotation.

15. Explain the difference between first-level cache and second-level cache?


Hibernate framework has 2 cache types known as first-level cache and second-level cache. Here is the difference between the 2 caches:

First Level CacheSecond Level Cache
The first level cache belongs to the session object. It cannot be shared with multiple or other sessions. The second level cache belongs to the SessionFactory object. It can be shared among multiple or all sessions in Hibernate Framework.
This cache is enabled by default in the application. It cannot be disabled by any means.This cache is usually disabled by default in the application. It can be enabled through configuration. 
This cache is available only until the session is open. After the session is closed, the cache is destroyed. This cache is available through the life cycle of the application. This cache is destroyed only when the application is restarted. Then, the cache is recreated.  

In hibernate framework, if an entity or object is loaded using the get() function, the hibernate checked the first level cache first. If the function does not find the object, it goes to the second level cache after configuration. If the object is still not found, then it goes to the database and returns the object. If there is no corresponding row in the table, the entity returns as null.

16. What is One-to-Many association in Hibernate framework?


In the hibernate framework, one object can be associated with multiple or different objects. This is called One-to-Many association. The One-to-Many mapping is carried out using Set Java collection. Set Java collection which does not have any redundant elements are used. The One-to-Many element in Set Java displays the relation between one object and multiple objects.
Here is an example of the usage of the One-to-Many annotation:
An example of a person who has multiple cars is taken


@Entity
@Table(name=”Person”)
public class Person

Here is an example of how Many-to-One annotation can be used:
The car class is displayed below.
@Entity
@Table(name=”Car”)
public class Car

// getters and setters
}

17. Explain Hibernate Configuration File?


Hibernate Configuration File is also known as hibernate.cfg.xml. This is one of the most important and commonly used configuration files in Hibernate framework. This configuration file is stored under the src/main/resource folder, by default. The hibernate.cfg.xml contains configuration related to the database and configuration related to the session. Hibernate framework provides the configuration in 2 files, either in an XML file such as hibernate.cfg.xml or a property file such as hibernate.properties.
The hibernate configuration file is used to ascertain the following information:
It is used to define database connection details such as driver class, URL, username and password.
Each database used in the application has one configuration. To connect with two databases,2 configuration files with different names must be created.
The hibernate framework properties are: dialect, show_sql, second_level_cache, and mapping file names.

18. What is the Many-to-Many association in hibernate framework?


A @ManytoMany annotation and an entity attribute are required in the Many-to-Many mapping. This association can either be uni-directional or bi-directional. Under unidirectional attributes, the attributed model the association and the developers use the association to navigate it in their domain model or JPQL queries. The annotation plays the role of telling the framework to map a Many-to-Many association. Under the bidirectional association, the Many-to-Many mapping helps the developer in navigating the association in both directions.

19. How does one create an immutable class in the hibernate framework?


The immutable class in the hibernate framework is used as follows:
If the developer uses the XML form of the configuration, a class can be made immutable with the help of the markingmutable=false.
The default value of the element is true. Hence, it indicates that the class is not created by default.
The developer can also use annotations to make an immutable class in hibernate. It is created by using the annotation @Immutable.

20. How does one integrate hibernate framework with Spring?


Spring is one of the most commonly used and popular Java frameworks today. Spring is a type of JavaEE framework, whereas, Hibernate is one of the most popular ORM frameworks. Hence, the Spring and Hibernate combination is used by the various enterprise application.
Here are the steps to be followed to integrate the Spring framework and Hibernate framework:
The developer is required to ass the hibernate-entity manager, hibernate-core and Spring-ORM dependencies.
Then, the developer must create model classes and the respective DAO implementations required for the database operations. The DAO classes use SessionFactory. This is inserted in the framework by the Spring Bean configuration.
The developer is also required to note that they need not use Hibernate Transaction Management. This is because the Spring declarative will take care of it using the annotation @Transactional annotation.

21. Explain Hibernate Inheritance Mapping in detail.


Inheritance is one of the most crucial elements in object-oriented principles in Java, as Java is an Object-Oriented Programming Language. Inheritance in Java is used to represent models as it simplifies the relationship. However, inheritance is not supported by relational databases as they have a flat structure.
The inheritance Mapping strategies here take care of solving how to hibernate. Since hibernate is an ORM, it tries to map the problem. This is done in between the Inheritance of Java and flat structures of Databases.
For instance, a class diagram of Inheritance Mapping is displayed below:

The different types of Inheritance Mapping Strategies available are:
Mapped Super Class strategy
Joined Table strategy
Table Per the Class strategy
Single Table Strategy

22. Is Hibernate framework prone to SQL injection attacks?


In terms of wen security, Hibernate framework is susceptible to SQL injection attacks. Here, the hacker can attack the queries made by the application or the website to the database. Therefore, the attacker is slowed to view sensitive data which is usually not retrievable. The attacker can also modify or remove data from here which results in damaging the application’s behaviour.
No immunity is provided by Hibernate framework against SQL Injection attacks. But precautions can be taken to prevent such attacks.

The following practices must be followed:

  • The user can incorporate prepared statements which use Parameterized queries.
  • The developer can also use stored procedures.
  • Input validation can be performed to ensure data sanity.

Here are some of the commonly asked Hibernate framework questions for intermediate candidates:

1. What is a hibernate mapping file?


The hibernate mapping file is a type of XML file. It is used to define the entity bean fields and respective database column mappings. The hibernate mapping files are used in the projects when third-party classes are required where hibernating JPA annotations cannot be used.


Here is an example of the hbm.xml file:

<?xml version = “1.0” encoding = “utf-8”?>

<!DOCTYPE hibernate-mapping PUBLIC 

“-//Hibernate/Hibernate Mapping DTD//EN”

“http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd”>

<hibernate-mapping>

   <!– What class is mapped to what database table–>

  <class name = “InterviewBitEmployee” table = “InterviewBitEmployee”>

     <meta attribute = “class-description”>

        This class contains the details of employees of InterviewBit. 

     </meta>

     <id name = “id” type = “int” column = “employee_id”>

        <generator class=”native”/>

     </id>

     <property name = “fullName” column = “full_name” type = “string”/>

     <property name = “email” column = “email” type = “string”/>

  </class>

</hibernate-mapping>

2. Explain a few important annotations used in hibernate mapping.


Hibernate framework supports JPA annotations. Here are some of the commonly used annotations:
javax.persistence.Entity: This annotation is used with the model classes. It is used to specify that they are entity beans.
javax.persistence.Table: This annotation is used with entity beans. They define the respective table name in the database.
Javax.persistence.Access: This annotation is used to define the access type, field or property. The default value in the framework is a field. In case the developer wants the framework to use getter-setter methods, they need to get it to a property.
Javax.persistence.EmbeddedId: This annotation is used to help in defining a composite primary key in the entity bean.
Javax.persistence.Column: This annotation helps the developer in defining the column name in the database table.
Javax.persistence.GeneratedValue: This annotation is used to define the strategy which must be used to generate the primary key. This annotation is also used in conjunction with the annotation javax.persistence.GenerationType.
Javax.persistence.OnetoOne: This annotation is used in defining the one-to-one mapping association between two bean entities. Hibernate framework also provides other annotations to define different mapping types such as One-to-Many, Many-to-One and Many-to-Many.
Org.hibernate.annotation.Cascade: This annotation is used by developers to define the cascading action. It is done between two bean entities.

3. How to get the Session function in Hibernate?


In hibernate, the session function is the layer between the Java application and the Hibernate framework. This function helps in weaving a connection with the database. This object is lightweight and is initiated every time an interaction is required with the database. This object helps in creating, reading, updating and deleting operations for a constant object.
To use this object, the developer can execute HQL queries, SQL native queries using the Session object.

4. Explain Hibernate Architecture.

Hibernate architecture has many objects. These objects include persistent object, session factory, session, query, transaction and others. The hibernate framework applications are categorized into the following parts:

  • Java Application
  • Hibernate framework with configuration and mapping files
  • Internal API


The Internal API includes the following :
-JDBC which is also known as Java Database Connectivity
-JTA which is also known as Java Transaction API
-JNDI which is also known as Java Naming Directory Interface

  • Databases such as MySQL, PostgreSQL, Oracle and other databases.

The main elements of the hibernate architecture are as follows:
Session: A session in the Hibernate framework is an object. This object helps the developer in maintaining the connection between the Java object application and database. Session object also provides ways for storing, retrieving and modifying data from the database.
SessionFactory: SessionFactory provides the developer with an instance of Session. It is a factory class. It provides Session objects according to the configuration parameters. This helps in establishing a connection to the database.
Transaction: This object is used to specify the atomic unit of work. It also has methods that are useful for transaction management. This object is optional.
ConnectionProvider: This is a part of JDBC connection objects. It is used to provide an abstraction to the framework from the DriverManager. This object is also optional.
TransactionFactory: This factory consists of Transaction objects. It is also optional.

5. Explain the difference between openSession and getCurrentSession?


The main differences between openSession and getCurrentSession as follows:

getCurrentSession()openSession()
This object is used to return the session that belongs to the context.This object is always used to open a new session.
This session object is bound to the hibernate context. In order to make this object work, the developer must modify the hibernate configuration file by adding <property name= “hibernate.current_session_context_class” > thread </property>. If this extension is not added, the session object will not give a HibernateException.In this object, a new session must be created for each request under a multi-threaded environment. Therefore, no property is required to be configured to make this session object work. 
Once the session factory is closed, this session object also gets closed.Here, the developer is required to close this session object after all the database operations are done. 
This session object is faster than openSession() under a single-threaded environment. This session object is slower than getCurrentSession() under a single-threaded environment. 

6. How to configure a Hibernate file?


To configure a hibernate file, the followed steps must be followed:
The developer is first required to identify the Plain Old Java Objects or the POJOs which have a database representation.
Then, one must identify which Plain Old Java Objects properties must be continued.
Each of the Plain Old Java Objects must be annotated in order. This is done to map the Java Objects to the column in a database table.
Then, the developer must create a database scheme using the scheme export tool that uses the existing database. Alternatively, one’s database scheme can be created.
Hibernate Java libraries must be added to the application’s classpath.
A hibernate XML configuration file must be created pointing to the database and the mapped classes.
One can then create a Hibernate Configuration object that refers to the XML configuration file, in the Java application.
A Hibernation SessionFactory object from the configuration object must also be built.
Then, the developer must retrieve the Hibernate Session objects from the SessionFactory. They are also required to write down the data access logic for the Java application in terms of creating, retrieve, update and delete.

7. State the differences between save() and saveOrUpdate() methods in hibernate session.


The similarity between these objects is that both these methods help in saving records to the table in the database when no records with the primary key in the table are available.
The main differences between save() and saveOrUpdate() are as follows:

Save()saveOrUpdate()
This object helps in generating a new identifier and INSERT a record into the database.Session.saveOrUpdate() object can use either INSERT or UPDATE. This is decided based on the existence of a record.
In this object, the insertion fails in case the primary key is already existing in the table.In this object, if the primary key already exists, the record is updated.
Here, the return type is serializable. This is the newly generated identifier id value as a Serializable object.Here, the return type of the saveOrUpdate() method is void.
The Save() object is used by developers to bring only the transient object to the persistent state.The saveOrUpdate() method brings both transient and detached objects into a persistent state. This session is also used to re-attach any detached object into a Session.

In terms of use, saveOrUpdate() is more flexible. However, this object involves extra processing in ascertaining whether a record already exists in the table or not.

8. Name and explain the key components of a Hibernate configuration object.


The hibernate configuration offers 2 key components. These key components are:
Class Mapping Setup: This component helps in creating a connection between Java classes and database tables.
Database Connection: This component helps in one or more configuration files.

9. Differentiate between get() and load() in the Hibernate session.


These methods generally help in getting data from the database.
The main differences between get() and load() are as follows:

get()load()
This session object gets the data from the database immediately after it is called.This session object helps in returning a proxy object. It loads the data only when it is required.
Here, the database is hit every time the get() is called.Here, the database is hit only when required. This is called Lazy Loading and improves the work of the method.
This method gives back a null if the object is not found in the database.This method gives back an ObjectNotFoundException if the object is not found in the database.
This method is generally used when the developer is not sure of the existence of the data in the database. This method is generally used when the developer is sure that the data exists in the database.

10. Explain Collection in Hibernate framework.


Hibernate framework provides functions that help in sustaining the Collections. A Collection can be a List, Set, Map, Collection, Sorted Set or Sorted Map. Some of the real interface types to sustain the collection-value fields are java.util.List, java.util.Set, java.util.Collection. Hibernate also injects Collections according to the type of interface. These instances behave like the types of value behaviour.

11. Explain criteria API in Hibernate.


In hibernate framework, the criteria API helps developers build dynamic criteria queries on a persistence database. Criteria API is more powerful and flexible than Hibernate Query Language queries to create dynamic queries.
The criteria API helps in programmatically developing criteria query objects. Here, the interface org.hibernate.Criteria are used for all purposes. Also, the createCritera() method in the session interface is executed. It takes the persistent object’s class or its entity name as the parameters and returns the persistence object when the criteria are executed.
The API also makes it easy to inject restrictions to selectively retrieve data from the database. This can be done by using the add() method. The org.hibernate.criterion.Criterion object is used in representing individual restriction.

Here is an example of the usage of criteria API:

Returning all the data of InterviewBitEmployee entity class:
Retriving objects whose property has value equal to the restriction, we use Restrictions.eq() method. For example, to fetch all records with name ‘Hibernate’:
Getting objects whose property has the value “not equal to” the restriction, we use Restrictions.ne() method. For example, to fetch all the records whose employee’s name is not Hibernate:
Retrieving all objects whose property matches a given pattern, we use Restrictions.like() (for case sensitivenes) and Restrictions.ilike()(for case insensitiveness):
The API criteria also has other methods such as isNull(), is notnull(), get(), get(), let() etc. These are used for adding more varieties of restrictions. Also, for Hibernate 5 onwards, the functions returning an object of typeCriteria are deprecated. Hibernate 5 versions have interfaces such as CriteriaBuilder and CriteriaQuery to facilitate the purpose. Here is an example:
To introduce restrictions in CriteriaQuery, a developer can use the CriteriaQuery.where method. This method is analogous to using the WHERE clause in the JPQL queries.


12. Name the collection types in the Hibernate framework.


In the hibernate framework, there are 5 types of collections used for one-to-many relationship mapping. These five types are:

  • Bag
  • Set
  • Array
  • Map
  • List

13. Explain HQL.


HQL is also known as Hibernate Query Language. This is an extension of SQL. Using this is very simple, efficient and flexible. It is easy to perform complex and difficult operations on relational databases without writing complicated queries using the HQL. HQL is an object-oriented representation of query language. Hence, the class name is used here instead of using the table name. The class name makes the language-independent of any database.
The HQL utilises the Query interface that is provided by Hibernate. The Query object is called using the createQuery() method. This is a part of the Session interface in hibernate framework.

The commonly used methods of the Hibernate Query Language are as follows:
Public int executeUpdate(): This is used to run the update/delete query.
Public Query setFirstResult(int row number): This is a method that accepts the row number as a parameter. This parameter is used to retrieve the record of the row number.
Public List list(): This returns the result as a list.
Public query setMaxResult(int rowsCount): This helps in returning a maximum up to the specified rowCount during retrieval from the database.
public Query setParameter(int position, Object value): This is used in setting the value to the attribute/column at a particular position. It also follows the JDBC style of the query parameter.
public Query setParameter(String name, Object value): This also helps in setting the value to a named query parameter.

Here is an example:


Getting a list of all records from InterviewBitEmployee Table:


Query query=session.createQuery(“from InterviewBitEmployee”);
List list=query.list();
System.out.println(list.get(0));

14. Explain a Hibernate Template Class.


When a Spring and Hibernate framework are integrated, the Spring ORM gives two helper classes. These are known as HibernateDaoSupport and HibernateTemplate. These two classes are used to get the Session from Hibernate and Spring Transaction Management.
In the Hibernate 3.0.1, the developer can use the SessionFactory getCurrentSession() method. This method helps in providing the current session.
The advantage of using the Template class includes the exception translation. However, this can also be done through @Repository annotation along with the service classes.

15. What are the advantages of Hibernate Template?


The advantages of using Hibernate Template are as follows:
The Template class has the ability to close the Automated Session.
By using the Template class, the interaction with the hibernate Session is easier.
Using the Template class automates exception handling.

16. What is session.lock() in hibernate framework?


The session.lock() is a method in the hibernate framework which is used to re-attack any detached object to the session.
The one drawback of this method is that it does not check for data synchronization between database and object in the persistence context. Hence, re-attachment may lead to a loss of data synchronization.

17. Explain the design patterns in Hibernate framework.


The design patterns used in the hibernate framework are:
Domain Model Pattern: This object model helps in incorporating behaviour and data.
Data Mapper: This object model is a layer of the map. It moves data between objects and a database. While doing this, it keeps the data independent of each other and independent of the map.
Factory Pattern: This object model is used in SessionFactory.
Proxy Pattern: this object model is used for lazy loading.

18. Explain Hibernate caching.


Hibernate caching is a strategy that is used for improving the performance of the application. It is done by pooling objects in the cache. This way, the queries are executed at a faster pace. The caching is useful when the same data that is executed multiple times has to be fetched. The data can be accessed from the cache, instead of hitting the database. This reduces the throughput time of the application.

19. Explain the use of the merge() method.


The merge () method is usually used to update existing values. This method helps create a copy from the entity object and return it once the existing values are updated. The result object enters the persistent context, which is later tracked for changes. The object initially used is not followed.

20. What is the hibernate validator framework?


Data validation is a crucial part of the hibernate framework. The data validation is also used with Javascript and server-side in the presentation layer before processing. This occurs before persisting in order which ensures that it follows the right format. Validation must be kept away from the business logic as it is a cross-cutting task. The Hibernate Validator gives the reference implementation of the bean validation specs.

Here are some of the commonly asked hibernate interview questions for experienced:


1. Can the Entity class be declared final?


No, the entity class is not defined as final. This is because the hibernate uses proxy classes and objects for lazy loading. Hence, it hits the database only when it is needed. This can be done by extending the entity bean. However, if the entity class is made final, the entity bean cannot be developed. Therefore, lazy loading will not be supported.

2. Explain Hibernate tuning.


Hibernate tuning is defined as optimizing the performance of Hibernate applications.
The various performance tuning strategies of Hibernate are as follows:

  • SQL Optimization
  • Session Management
  • Data Caching

3. Explain the states of a persistent entity.


The different states of a persistent entity are as follows:
Transient:
The transient state of an object is the initial state. The object enters the transient state once the instance of the entity class is created. They exist in heap memory. In the transient state, the object is not linked to a session. Hence, the object is not related to any database. This leads to no effect on the data in the database when any changes take place.


Here an example of the transient state:


InterviewBitEmployee employee=new InterviewBitEmployee();
//The object is in the transient state.
employee.setId(101);
employee.setFullName(“Hibernate”);
employee.setEmail(“hibernate@interviewbit.com”);
Persistent:
The object enters the persistent state when it is linked or associated with the session. For example, when one saves an object in the database, the object is in a persistence state. In the database table, each object corresponds to the row. Modifications to the data in this state lead to change in the record in the database.
The methods that can be used on the persistence object are:
session.save(record);
session.persist(record);
session.update(record);
session.saveOrUpdate(record);
session.lock(record);
session.merge(record);
Detached:
An object is said to be detached when the session is closed, or the cache is closed. This data is no longer a part of the session. Hence, changes in the object will not be reflected in the row of the database.
The methods that can be used on a detached are:
session.close();
session.clear();
session.detach(record);
session.evict(record);

Conclusion

The goal of the Hibernate framework is to free the developer from complex tasks and configurations related to shared data persistence. This is done through efficient and, above all, abstract mapping of POJO objects to database tables. Thus, the developer does not need to know the underlying complications. With the abstraction, queries can be run very efficiently, all of which help developers save a lot of development time. Hopefully, the above questions can help the applicant in getting a lead in interviews.

More Resources : jobs in Vijayawada | work from home jobs in Delhi | logical questions for interview | codeigniter interview questions

- Advertisement -spot_img

More articles

spot_img

Latest article

Build resume using templates

Explore urgently hiring jobs

Personalized jobs for you