Hibernate Interview Questions
1. What is ORM?
- ORM stands for Object Relational Mapping.
- It maps the data between Java Objects(application) and relational database.
- ORM Tools :- Hibernate ,MyBatis etc.
2.What is JPA?
- JPA Stands for Java Persistence API.
- JPA is a Specification.
- It specifies how to access, manage and persist data with database.
- Hibernate is one of the implementations of JPA.
- 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:
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
4. What is Hibernate?
- Hibernate is a java framework and ORM tool that is used to store, manipulate, and retrive data from the database.
- In simple way it is use to perform CRUD operations with database.
Advantages :
- Open-sourced and lightweight
- Fast performance
- Lazy loading
- Caching
5.Explain Hibernate Architecture.
- Java Application.
- Hibernate framework - Configuration and Mapping Files.
- Internal API -JDBC (Java Database Connectivity), JTA (Java Transaction API), JNDI (Java Naming Directory Interface).
- Database - MySQL, PostgreSQL, Oracle, etc.
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?
- HQL stands for Hibernate Query Language.
- It is the object-oriented Query Language of Hibernate Framework.
- HQL is very Similar to SQL except that uses class names instead of table.
Advantages :
- Easy to Learn
- Avoids complex queries.
- 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.
- MySQL
- Oracle
- PostgreSQL
- FrontBas
10.What are The Core Concepts of Hibernate?
- Configuration
- Session
- SessionFactory
- Criteria
- Query
- Transaction
11.Explain about SessionFactory Interface and is is Thread-Safe?
- This interface is responsible for the creation of session objects.
- It is created during application startup itself.
- one SessionFactory should be created per database in any application.
- 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?
- It Maintains a connection between the application and database.
- It provides methods to store, update, delete or fetch data from the database such as persist(), update(), delete(), load(), get() etc.
- It is a factory of Query, Criteria and Transaction.
- It is not thread-safe.
13.What is Transection?
- Transaction represents a unit of work.(set of sequential operations).
- Transection only completes if all operations completed successfully.
- Example :- Sending amount to someone through online.
- Transection is associated with Session and instantiated by calling session.beginTransaction().
14.What is Hibernate Configuration?
- Hibernate configuration contains database configuration like database url, username, password and dialect etc.
- It is used to initialize SessionFactory.
- It is also contains mapping files and entity class details.
We can use any of the following two methods of hibernate configuration :
- XML based configuration (using hibernate.cfg.xml).
- Programmatic configuration(using code logic).
15.What is Criteria in Hibernate?
- It is used to retrieve data from the database.
- The object of Criteria can be obtained by calling the createCriteria() method of Session interface.
- ex. Criteria cr = session.createCriteria(Employee.class);
16.What is Query in Hibernate?
- It is used to retrieve/modify data from database.
- The object of Query is obtained by calling createQuery() method of Session interface.
- 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);
session.save(emp);
Detached state :
If session is closed, hibernate is no longer aware about this object.
session.close();
Step 2: Configure the Database In the application.properties file, configure the database settings as follows:
Step 3: Create the Model Class Create a model class that represents the table you want to map. For example:
Step 4: Create the Repository Interface Create a repository interface that extends the JpaRepository interface provided by Spring Data JPA. For example:
Step 5: Create the Service Class Create a service class that uses the repository to perform CRUD operations on the database. For example:
Step 6: Use the Service Class in the Controller Create a controller class that uses the service class to handle HTTP requests. For example:
Spring Boot application is now integrated with Hibernate, and we can perform CRUD operations on the database using the service class and repository interface.
session.close();
Note : The detached objects can be moved again to persistent state if save/update or other methods are called.
17.What is Lazy Loading in Hibernate?
- Lazy loading in Hibernate means fetching and loading the data, only when it is needed, from a persistence storage like a database.
- Advantage :- Improved performance of data fetching.
- By default lazy loading is true.
- 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?
- It inserts new record if it is not there in the database.
- 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?
- Hibernate caching acts as a layer between the actual database and your application
- 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>
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
@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
}
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
@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);
}
}
@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); }
}
26.What are Some Annotations in the Hibernate?
- @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.
- @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.
- @Id: This annotation is used to mark a field as the primary key of the entity.
- @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.
- @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.
- @JoinColumn: This annotation is used to specify the join column that is used to join two entities in a relationship.
- @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?
- 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.
- 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.
- 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.
- 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.
No comments:
Post a Comment