Tuesday, March 28, 2023

Hibernate Interview Questions : 2023

Hibernate is a widely used Object-Relational Mapping (ORM) tool that simplifies the development of Java applications by providing a framework for data persistence. It maps Java classes to database tables and vice versa, allowing developers to interact with databases using an object-oriented approach. If you are preparing for a Java interview, here are some common Hibernate interview questions you might encounter: 

Hibernate Interview Questions





Hibernate Interview Questions


1. What is ORM?

  1. ORM stands for Object Relational Mapping.
  2. It maps the data between Java Objects(application) and relational database.
  3. ORM Tools :- Hibernate ,MyBatis etc. 
What is ORM




2.What is JPA?

  1. JPA Stands for Java Persistence API.
  2. JPA is a Specification.
  3. It specifies how to access, manage and persist data with database.
  4. Hibernate is one of the implementations of JPA.
  5. Hibernate follows the standards of JPA. 

3.What is the architecture of JPA?

The architecture of JPA is based on several components, which work together to provide a complete ORM solution:

  1. Entity: An entity is a persistent object that represents a row in a database table. It is a plain old Java object (POJO) annotated with the @Entity annotation.
  2. EntityManager: The EntityManager is the main component of JPA. It provides the API for managing entities and their lifecycle, including creating, updating, deleting, and querying entities.
  3. Persistence Unit: A persistence unit is a collection of entity classes and other configuration information. It is defined in the persistence.xml file, which is typically located in the META-INF directory of the application.
  4. Entity Manager Factory: The EntityManagerFactory is responsible for creating EntityManager instances. It is obtained from the PersistenceProvider and is typically created only once during the application lifecycle.
  5. Query: A Query is used to retrieve data from the database using JPA's query language (JPQL). It is created using the EntityManager.createQuery() method and can be executed using the Query.getResultList() or Query.getSingleResult() methods.
  6. Transaction: A transaction is a set of operations that must be executed as a single unit of work. JPA provides a Transaction API that allows developers to manage transactions programmatically.
What is the architecture of JPA?




JPA provides a standard API for Object-Relational Mapping that simplifies the development of Java applications that interact with databases. Its architecture is based on several key components, including entities, the EntityManager, persistence units, the EntityManagerFactory, queries, and transactions. By using JPA, developers can focus on the business logic of their applications rather than the database access layer, resulting in increased productivity and simpler code.

4. What is Hibernate?

  1. Hibernate is a java framework and ORM tool that is used to store, manipulate, and retrive data from the database.
  2. In simple way it is use to perform CRUD operations with database.

Advantages :
  1. Open-sourced and lightweight
  2. Fast performance
  3. Lazy loading
  4. Caching

5.Explain Hibernate Architecture.

The Hibernate architecture consists of many objects such as a persistent object, session factory, session, query, transaction, etc. Applications developed using Hibernate is mainly categorized into 4 parts:
  1. Java Application.
  2. Hibernate framework - Configuration and Mapping Files.
  3. Internal API -JDBC (Java Database Connectivity), JTA (Java Transaction API), JNDI (Java Naming Directory Interface).
  4. Database - MySQL, PostgreSQL, Oracle, etc.
Hibernate Architecture




In Stage I, we will write the persistence logic using Hibernate Configuration and Hibernate mapping files to perform specific operations on the database. We will then create an object of the class on which the persistence logic is written. 
In Stage II, the class containing the persistence logic will interact with the Hibernate framework, which provides abstractions to perform certain tasks. Hibernate is responsible for executing the persistence logic using the internal implementation layers below the Hibernate framework.
 In Stage III, the Hibernate framework interacts with JDBC, JNDI, JTA, etc. to perform the persistence logic. 
In Stages IV and V, Hibernate interacts with the database through the JDBC driver to execute CRUD operations. If the persistence logic retrieves a record, it will be displayed on the console of our Java program in the form of an Object, in the reverse order.

6.What is HQL?

  1. HQL stands for Hibernate Query Language.
  2. It is the object-oriented Query Language of Hibernate Framework.
  3. HQL is very Similar to SQL except that uses class names instead of table.
Advantages :
  1. Easy to Learn
  2. Avoids complex queries.
  3. Database Independent.

7.Difference Between JDBC and Hibernate.


JDBC

HIBERNATE

1.Database connectivity technology 1.It is a Java Framework
2.Uses SQL 2.Uses HQL
3. More coding required and Less performance 3. Removes boiler-plate code and improved performance
4.Database Dependent 4.Database independent

8.Difference Between Hibernate and JPA.


JPA

HIBERNATE

1.Java Persistence API (JPA) defines the management of relational data in the Java applications. 1.Hibernate is an Object-Relational Mapping (ORM) tool which is used to save the state of Java object into the database.
2.It is just a specification. Various ORM tools implement it for data persistence. 2.It is one of the most frequently used JPA implementation.
3.It is defined in javax.persistence package. 3.It is defined in org.hibernate package.
4.The EntityManagerFactory interface is used to interact with the entity manager factory for the persistence unit. Thus, it provides an entity manager. 4.It uses SessionFactory interface to create Session instances.
5.It uses EntityManager interface to create, read, and delete operations for instances of mapped entity classes. This interface interacts with the persistence context. 5.It uses Session interface to create, read, and delete operations for instances of mapped entity classes. It behaves as a runtime interface between a Java application and Hibernate.
6.It uses Java Persistence Query Language (JPQL) as an object-oriented query language to perform database operations. 6.It uses Hibernate Query Language (HQL) as an object-oriented query language to perform database operations.

9.List some of the databases supported by Hibernate.

  1. MySQL
  2. Oracle
  3. PostgreSQL
  4. FrontBas

10.What are The Core Concepts of Hibernate?

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

11.Explain about SessionFactory Interface and is is Thread-Safe?

  1. This interface is responsible for the creation of session objects.
  2. It is created during application startup itself.
  3. one SessionFactory should be created per database in any application.
  4. It is a thread-safe object and used by all the threads of an application.

12.Explain about Session interface and is it Thread-Safe?

  1. It Maintains a connection between the application and database.
  2. It provides methods to store, update, delete or fetch data from the database such as persist(), update(), delete(), load(), get() etc.
  3. It is a factory of Query, Criteria and Transaction.
  4. It is not thread-safe.

13.What is Transection?

  1. Transaction represents a unit of work.(set of sequential operations).
  2. Transection only completes if all operations completed successfully.
  3. Example :- Sending amount to someone through online.
  4. Transection is associated with Session and instantiated by calling session.beginTransaction().

14.What is Hibernate Configuration?

  1. Hibernate configuration contains database configuration like database url, username, password and dialect etc.
  2. It is used to initialize SessionFactory.
  3. It is also contains mapping files and entity class details.

We can use any of the following two methods of hibernate configuration :
  1. XML based configuration (using hibernate.cfg.xml).
  2. Programmatic configuration(using code logic).

15.What is Criteria in Hibernate?

  1. It is used to retrieve data from the database.
  2. The object of Criteria can be obtained by calling the createCriteria() method of Session interface.
  3. ex. Criteria cr = session.createCriteria(Employee.class);

16.What is Query in Hibernate?

  1. It is used to retrieve/modify data from database.
  2. The object of Query is obtained by calling createQuery() method of Session interface.
  3. ex. Query q = session.createQuery("select max(salary) from Emp");

17. What are the different states of objects in Hibernate?

Transient State :

when the object is created newly and not associated with session. 
Employee emp = new Employee(1,"Kartik");


Persistent State :

If session is open and operation are performed and all the changes to this object will be tracked by hibernate.
session.save(emp);


Detached state : 

If session is closed, hibernate is no longer aware about this object.
session.close();

Note : The detached objects can be moved again to persistent state if save/update or other methods are              called.

states of objects in Hibernate





17.What is Lazy Loading in Hibernate?

  1. Lazy loading in Hibernate means fetching and loading the data, only when it is needed, from a persistence storage like a database.
  2. Advantage :- Improved performance of data fetching.
  3. By default lazy loading is true.
  4. we can override it  :- @Lazy(value = false).

18.Difference Between Lazy and Eager Loading in Hibernate.


Lazy Loading

Eager Loading

1.In Lazy loading, associated data loads only when we explicitly call getter or size method. 1.In Eager loading, data loading happens at the time of their parent is fetched
2.ManyToMany and OneToMany associations used lazy loading strategy by default. 2.ManyToOne and OneToOne associations used lazy loading strategy by default
3.It can be enabled by using the annotation parameter : fetch = FetchType.LAZY 3.It can be enabled by using the annotation parameter : fetch = FetchType.EAGER
4.Initial load time much smaller than Eager loading 4.Loading too much unnecessary data might impact performance

19.What is saveOrupdate() methods?

  1. It inserts new record if it is not there in the database.
  2. If the record already there, then it is update it.

20.What is the difference between save() and persist() method?


Save()

Persist()

1.It inserts a new record if record not there in database. If record alredy there in database, save method will be fail. 1.It can Only save object within the transection boundaries.
2.Syn: public Serializable save(Object o) Returns the identifier (Serializable) of the instance. 2.Syn: public void persist(Object o) Return nothing because its return type is void.


21.What is the difference between get() and load() method?


get()

load()

1.Returns null if an object is not found. 1.Throws ObjectNotFoundException if an object is not found.
2.get() method always hit the database. 2.load() method doesn't hit the database.
3.It returns the real object, not the proxy. 3.It returns proxy object.
4.It should be used if you are not sure about the existence of instance. 4.It should be used if you are sure that instance exists.


22.Difference Between getCurrentSession() and openSession() methods?


getCurrentSession()

openSession()

This method returns the session bound to the context. This method always opens a new session.
This session object gets closed once the session factory is closed. It's the developer’s responsibility to close this object once all the database operations are done.
In a single-threaded environment, this method is faster than openSession(). In single threaded environment, it is slower than getCurrentSession()

23.What is Hibernate Caching?

  1. Hibernate caching acts as a layer between the actual database and  your application
  2. It reduce the time taken to obtain the required data as it fetches from memory instead of directly hitting the database.

24. Types Of Caching Or What is the difference between first level cache and second level cache?


First Level Cache

Second Level Cache

1.It is the first place that Hibernate checks for cached data. 1.It is checked if data is not found in first level cache.
2.It is enabled by default and session object holds the first cache data. 2.SessionFactory object holds this data and need to enabled explicitly
3.This will not be available to entire application. 3.This will be available to entire application.


25.How to Integrate Hibernate with Spring Boot?

Step 1: Add the required dependencies In the pom.xml file of your Spring Boot project, add the following dependencies:



<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-data-jpa</artifactId> 
</dependency> 
<dependency> 
<groupId>org.hibernate</groupId> 
<artifactId>hibernate-core</artifactId> 
<version>5.4.32.Final</version> 
</dependency> 
<dependency> 
<groupId>com.h2database</groupId> 
<artifactId>h2</artifactId> 
<scope>runtime</scope> </dependency>

Step 2: Configure the Database In the application.properties file, configure the database settings as follows:



spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=create

Step 3: Create the Model Class Create a model class that represents the table you want to map. For example:



@Entity 
@Table(name = "employees"
public class Employee { 
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) 
 private Long id;
@Column(name = "first_name"
 private String firstName; 
@Column(name = "last_name"
 private String lastName; 
// getters and setters 
}

Step 4: Create the Repository Interface Create a repository interface that extends the JpaRepository interface provided by Spring Data JPA. For example:



public interface EmployeeRepository extends JpaRepository<Employee, Long> { }

Step 5: Create the Service Class Create a service class that uses the repository to perform CRUD operations on the database. For example:



@Service 
public class EmployeeService
@Autowired 
private EmployeeRepository employeeRepository; 
public List<Employee> getAllEmployees() { 
return employeeRepository.findAll(); 
 } 
public Employee getEmployeeById(Long id) { 
return employeeRepository.findById(id).orElse(null); 
 } 
public Employee addEmployee(Employee employee) { 
return employeeRepository.save(employee); 
 } 
public void deleteEmployee(Long id) { 
 employeeRepository.deleteById(id); 
 } 
}

Step 6: Use the Service Class in the Controller Create a controller class that uses the service class to handle HTTP requests. For example:



@RestController 
@RequestMapping("/api/v1/employees"
public class EmployeeController { 
@Autowired 
 private EmployeeService employeeService;
@GetMapping public List<Employee> getAllEmployees() { 
return employeeService.getAllEmployees(); 
 } 
 @GetMapping("/{id}") public Employee getEmployeeById(@PathVariable Long id) { return employeeService.getEmployeeById(id); 
 } 
 @PostMapping public Employee addEmployee(@RequestBody Employee employee) { 
return employeeService.addEmployee(employee); 
 }
 @DeleteMapping("/{id}") public void deleteEmployee(@PathVariable Long id){ 
return employeeService.deleteEmployee(id); 
 } 
}

 Spring Boot application is now integrated with Hibernate, and we can perform CRUD operations on the database using the service class and repository interface.

26.What are Some Annotations in the Hibernate?

  1. @Entity: This annotation is used to mark a Java class as an entity or a table in the database. The name of the entity defaults to the name of the Java class, but it can be overridden using the name attribute of the annotation.
  2. @Table: This annotation is used to specify the name of the database table that corresponds to the entity. It can also be used to specify other properties of the table such as the schema name and catalog name.
  3. @Id: This annotation is used to mark a field as the primary key of the entity.
  4. @GeneratedValue: This annotation is used to specify the strategy for generating the primary key values. There are several strategies available such as AUTO, IDENTITY, SEQUENCE, TABLE, and UUID.
  5. @Column: This annotation is used to map a Java field to a database column. The name of the column defaults to the name of the Java field, but it can be overridden using the name attribute of the annotation.
  6. @JoinColumn: This annotation is used to specify the join column that is used to join two entities in a relationship.
  7. @Transient: This annotation is used to mark a field as transient, which means that it should not be persisted in the database.

27.How many Types of Association Mapping are possible in Hibernate?

  1. One-to-One mapping: This mapping is used to represent a relationship between two entities where each instance of one entity is associated with only one instance of the other entity.
  2. One-to-Many mapping: This mapping is used to represent a relationship between two entities where each instance of one entity is associated with multiple instances of the other entity.
  3. Many-to-One mapping: This mapping is used to represent a relationship between two entities where multiple instances of one entity are associated with only one instance of the other entity.
  4. Many-to-Many mapping: This mapping is used to represent a relationship between two entities where each instance of one entity is associated with multiple instances of the other entity, and vice versa.

28.What is the purpose of the hbm2ddl.auto property in Hibernate? 

The hbm2ddl.auto property is used to automatically generate database schema based on the entity mappings. It can be set to create, update, or validate the schema.

Conclusion

Hibernate is the most powerful open source ORM tool that is used for mapping java objects with the database structures at run time. These are just a few examples of Hibernate interview questions. It is important to prepare for the interview. Good luck!

No comments:

Post a Comment