0% found this document useful (0 votes)
12 views21 pages

Module-5 - Springs and Hibernates

The document, prepared by Mr. Lohith C, provides an overview of Advanced Java and J2EE, specifically focusing on Spring and Hibernate frameworks. It covers key features of Spring, its architecture, Inversion of Control (IoC), Dependency Injection (DI), bean scopes, lifecycle, and Spring MVC configuration. Additionally, it discusses request mapping, form handling, and validation in Spring MVC, providing examples and explanations of various concepts.

Uploaded by

lopezloyla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views21 pages

Module-5 - Springs and Hibernates

The document, prepared by Mr. Lohith C, provides an overview of Advanced Java and J2EE, specifically focusing on Spring and Hibernate frameworks. It covers key features of Spring, its architecture, Inversion of Control (IoC), Dependency Injection (DI), bean scopes, lifecycle, and Spring MVC configuration. Additionally, it discusses request mapping, form handling, and validation in Spring MVC, providing examples and explanations of various concepts.

Uploaded by

lopezloyla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Prepared by Mr. Lohith C, Professor, Department of Dr.

APJ Kalam School of Engineering

Subject: Advanced Java and J2EE


Module 5 - Springs and Hibernates
Prepared By Mr. Lohith C
Professor
Dept of APJ Abdul Kalam School of Engineering
Garden City University

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Features of Spring
1. Comprehensive Framework: Spring is a comprehensive framework that provides a
wide range of services, including security, transaction management, and web services
integration.
2. Modularity: Spring's modules allow you to use only the features that you need, such
as Spring Core, Spring MVC, Spring Data, etc.
3. Lightweight: The core container is lightweight, offering a minimal footprint while
still delivering robust functionality.
4. Aspect-Oriented Programming (AOP): Spring provides AOP capabilities that allow
you to separate cross-cutting concerns like logging, security, and transactions from
the business logic.
5. Transaction Management: Spring provides a consistent approach to transaction
management, allowing you to manage transactions declaratively (using annotations)
or programmatically.
6. Data Access: Spring simplifies working with databases, providing integration with
JDBC, JPA, Hibernate, and other data access frameworks.
7. Spring MVC: A comprehensive web module to build web applications with features
such as flexible mapping, form handling, and easy integration with various view
technologies (JSP, Thymeleaf).
8. Security: Spring Security is a customizable framework for securing applications, with
authentication, authorization, and encryption features.
9. Testing Support: Spring has excellent testing support, including integration with
JUnit, mock objects, and other testing tools.

Spring Architecture

1. Core Container:
o Core: Provides fundamental features such as the IoC container.
o Beans: Manages beans and their configurations.
o Context: Provides configuration management and the ability to access
application components.
o Spring AOP: Handles aspect-oriented programming functionality.
o JDBC and ORM: Integration with JDBC, JPA, and Hibernate for data
persistence.
o Web Module: Offers features like Spring MVC and WebSocket for building
web applications.
2. Beans Container: This is the heart of Spring’s IoC (Inversion of Control) container.
It manages the creation, lifecycle, and dependency injection of beans.
3. Aspect-Oriented Programming (AOP): Spring supports AOP, which allows
separating concerns like logging, transaction management, and security from business
logic.
4. Data Access/Integration: Spring provides simplified JDBC and ORM frameworks
for handling database operations, making it easier to integrate with various data
sources.
5. Web Layer: Includes components like Spring MVC for creating web applications and
support for RESTful web services.
6. Enterprise Layer: Spring provides enterprise features like messaging (JMS),
transaction management, and integration with JPA, Hibernate, etc.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Inversion of Control (IoC)


 Definition: Inversion of Control is a design principle where the control of object
creation, configuration, and lifecycle management is transferred from the application
to the Spring container.
 Purpose: It decouples the application’s components, allowing for easier management
and testing. Instead of the objects creating their dependencies, they are provided by
the Spring container.
 How IoC Works in Spring: The Spring container takes care of managing the objects'
lifecycle and injecting their dependencies, providing flexibility and modularity.

Dependency Injection (DI)

 Definition: Dependency Injection is a core concept in Spring and part of the IoC
pattern. It allows objects to be provided with their dependencies rather than creating
them internally, promoting loose coupling between components.

There are three main types of Dependency Injection in Spring:

1. Constructor Injection:
o Dependencies are provided to the class through its constructor.
o Example:

@Component
public class MyService {
private final MyRepository repository;

@Autowired
public MyService(MyRepository repository) {
this.repository = repository;
}
}

o Benefits:
 Makes dependencies immutable, ensuring that the object is always in a
valid state.
 Can be used in situations where dependencies are mandatory.
2. Setter Injection:
o Dependencies are set through setter methods after the object is constructed.
o Example:

@Component
public class MyService {
private MyRepository repository;

@Autowired
public void setRepository(MyRepository repository) {
this.repository = repository;
}
}

o Benefits:
 Allows optional dependencies.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

 Supports changes in the object state after construction.


3. Field Injection:
o Dependencies are injected directly into the fields, typically using the
@Autowired annotation.
o Example:

@Component
public class MyService {
@Autowired
private MyRepository repository;
}

o Benefits:
 Simplifies code by removing the need for setters or constructors.
 Not recommended for final or immutable fields since it makes the
object more difficult to test.

Bean Scope in Spring

Bean scope defines the lifecycle and visibility of Spring beans. Spring supports several types
of bean scopes:

1. Singleton (Default):
o One instance of the bean is created and shared across the entire Spring
container.
o Useful for stateless beans.
o Example:

@Component
public class MyService {
// Singleton bean by default
}

2. Prototype:
o A new instance of the bean is created every time it is requested from the
container.
o Useful for stateful beans or when you need independent instances.
o Example:

@Scope("prototype")
@Component
public class MyService {
// New instance every time requested
}

3. Request:
o A new bean is created for each HTTP request. It is only available in a web
application context.
o Useful for beans that need to be unique per HTTP request.
o Example:

@Scope("request")
@Component

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

public class MyService {


// Created for each HTTP request
}

4. Session:
o A new bean is created for each HTTP session. Available only in web
applications.
o Useful for beans that need to be unique per HTTP session.
o Example:

@Scope("session")
@Component
public class MyService {
// Created for each HTTP session
}

5. Application:
o A new bean is created for the entire application context and shared across the
application.
o Available only in a web environment and typically used for shared beans
across multiple sessions.
o Example:

@Scope("application")
@Component
public class MyService {
// Shared across the entire application
}

6. Websocket:
o A new bean is created for each WebSocket. This scope is used when
integrating with WebSocket communication.
o Example:

@Scope("websocket")
@Component
public class MyService {
// Created for each WebSocket connection
}

Bean Lifecycle in Spring

The lifecycle of a Spring bean involves several steps that the container follows from bean
creation to destruction:

1. Instantiation:
o The Spring container creates an instance of the bean based on its configuration
(via annotations or XML).
2. Populate properties:
o Spring injects the dependencies (via constructor or setter methods) into the
bean.
3. Bean Name Aware (optional):

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

o If the bean implements BeanNameAware, the container sets the name of the
bean.
4. BeanFactory Aware (optional):
o If the bean implements BeanFactoryAware, Spring provides a reference to the
BeanFactory for the bean to access other beans.
5. ApplicationContext Aware (optional):
o If the bean implements ApplicationContextAware, Spring provides the
ApplicationContext reference.
6. Custom Initialization (optional):
o If the bean has custom initialization logic (e.g., via @PostConstruct or init-
method), it will be invoked after properties are set.
7. Post-processing (optional):
o If the bean implements BeanPostProcessor, Spring calls
postProcessBeforeInitialization and
postProcessAfterInitialization methods.
o Used for tasks like modifying bean instances before or after initialization.
8. Ready for Use:
o The bean is fully initialized and ready for use by the application.
9. Destroy (optional):
o When the application context is closed, Spring calls the destroy-method (if
configured) or invokes @PreDestroy (if present) to clean up resources.

Dependency Injection Types

1. Constructor Injection:
o Dependencies are provided through the constructor of the class. Constructor
injection ensures that all dependencies are available when the bean is created,
and it can make the object immutable (no changes after construction).
o Example:

@Component
public class MyService {
private final MyRepository repository;

@Autowired
public MyService(MyRepository repository) {
this.repository = repository; // Dependency injected
through constructor
}
}

o Benefits:
 Ensures immutability of the object.
 Dependencies are mandatory and cannot be left uninitialized.
2. Setter Injection:
o Dependencies are provided through setter methods after the bean is created.
This allows optional dependencies and can be used to modify the object after
its construction.
o Example:

@Component
public class MyService {

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

private MyRepository repository;

@Autowired
public void setRepository(MyRepository repository) {
this.repository = repository; // Dependency injected
through setter method
}
}

o Benefits:
 Suitable for optional dependencies.
 Allows for flexibility in setting dependencies after object creation.
3. Field Injection:
o Dependencies are injected directly into fields using annotations like
@Autowired. Spring automatically injects the dependencies into the fields
without needing a constructor or setter.
o Example:

@Component
public class MyService {
@Autowired
private MyRepository repository; // Dependency injected
directly into the field
}

o Benefits:
 Simplifies the code by eliminating the need for constructors or setter
methods.
 Useful for quick, less complex configurations.
o Drawbacks:
 Not ideal for unit testing (because the dependencies are not explicitly
passed).
 Difficult to ensure immutability of the object.

Summary

 Bean Scope determines how a bean's lifecycle is managed in the Spring container
(e.g., Singleton, Prototype, etc.).
 Bean Lifecycle defines the various stages a Spring bean goes through, from
instantiation to destruction.
 Dependency Injection provides a way to inject dependencies into Spring beans using
different methods (Constructor, Setter, Field Injection), promoting loose coupling and
making testing easier.

Configuration of Spring MVC

Spring MVC is a powerful framework for building web applications, following the Model-
View-Controller (MVC) design pattern. Configuring Spring MVC involves setting up the
application context, creating controllers, and configuring the DispatcherServlet.

1. XML-based Configuration:

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

o You define the Spring configuration in the web.xml file and separate it into a
Spring configuration file (e.g., applicationContext.xml).
o web.xml configuration:

<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servle
t-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

o applicationContext.xml (for Spring beans and view resolver):

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-
4.3.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-
4.3.xsd">

<!-- Component scanning -->


<context:component-scan base-package="com.example" />

<!-- View Resolver -->


<bean
class="org.springframework.web.servlet.view.InternalResourceVie
wResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

2. Annotation-based Configuration (Java Config):


o Spring allows you to configure MVC using Java-based configuration with
@EnableWebMvc.
o WebConfig.java (Java-based Spring MVC configuration):

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example")
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry
registry) {
registry.addViewController("/").setViewName("home");
}

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

3. DispatcherServlet:
o The DispatcherServlet acts as the front controller in Spring MVC, routing
all HTTP requests to the appropriate handler methods in controllers.

Request-Mapping

@RequestMapping is used to map HTTP requests to handler methods in controllers. It is one


of the key annotations in Spring MVC.

1. Basic Usage:
o Map a method to a specific URL pattern and HTTP method (GET, POST,
etc.).
o Example:

@Controller
public class MyController {

@RequestMapping("/hello")
public String sayHello() {
return "hello"; // Returns the view name
}
}

2. Mapping with HTTP Methods:


o You can specify the type of HTTP method for request handling.
o Example:

@RequestMapping(value = "/submit", method = RequestMethod.POST)


public String submitForm() {
return "formSuccess";
}

3. Request Parameters:
o You can map parameters from the URL using @RequestParam or specify
request headers with @RequestHeader.
o Example:

@RequestMapping(value = "/greet", method = RequestMethod.GET)


public String greet(@RequestParam String name) {
return "Hello, " + name;
}

4. Path Variables:
o @PathVariable can be used to extract values from the URL.
o Example:

@RequestMapping("/user/{id}")
public String getUser(@PathVariable("id") String userId) {
return "User ID: " + userId;
}

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Spring MVC Form Tag Library

Spring MVC provides a set of form-related tags that help in building and managing forms
efficiently in JSP or other view technologies. The Spring Form Tag Library provides tags like
form:form, form:input, form:select, etc., which automatically handle form binding and
validation.

1. Form Tag Library:


o Add the form tag library to your JSP:

<%@ taglib uri="http://www.springframework.org/tags/form"


prefix="form" %>

2. Creating a Form:
o Use form:form to create a form, bind the form fields to a model object.
o Example:

<form:form modelAttribute="user" action="/submit"


method="POST">
<form:input path="name" label="Name" />
<form:input path="email" label="Email" />
<form:checkbox path="newsletter" label="Subscribe to
newsletter" />
<input type="submit" value="Submit" />
</form:form>

3. Binding Form Data:


o The modelAttribute attribute binds the form to a model object, which will be
populated with data on form submission.
o The path attribute on form fields binds individual fields to the model object’s
properties.
4. Form Validation:
o Spring Form tags can integrate with Spring’s validation framework, allowing
you to easily validate form inputs on the server side.

Spring Validation

Spring provides a way to validate user inputs in forms using annotations (@Valid or
@Validated) and custom validation logic. This can be integrated with the form tag library to
ensure data consistency and accuracy.

1. Validation Annotations:
o @NotNull: Ensures a field is not null.
o @Size: Specifies size constraints for a string or collection.
o @Email: Validates an email address.
o @Min/@Max: Specifies minimum and maximum values for a number.

Example:

public class User {


@NotNull
@Size(min = 2, max = 100)

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

private String name;

@Email
private String email;
}

2. Using @Valid for Form Validation:


o You can use the @Valid annotation to trigger validation of a model object
before processing the form data.
o Example in Controller:

@Controller
public class UserController {

@PostMapping("/submit")
public String submitUser(@Valid @ModelAttribute("user")
User user, BindingResult result) {
if (result.hasErrors()) {
return "form"; // Show form with errors
}
// Process form data
return "formSuccess";
}
}

3. BindingResult:
o BindingResult is used to hold the results of the validation. If there are
validation errors, they can be displayed in the view.
4. Custom Validators:
o You can create custom validation logic by implementing
org.springframework.validation.Validator interface.

Example:

public class UserValidator implements Validator {

@Override
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}

@Override
public void validate(Object target, Errors errors) {
User user = (User) target;
if (user.getEmail() == null ||
!user.getEmail().contains("@")) {
errors.rejectValue("email", "invalid.email", "Email must
contain '@'");
}
}
}

o Registering Custom Validator:


 You can register a custom validator in your configuration class or
directly in the controller.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Summary

 Spring MVC Configuration involves setting up the DispatcherServlet and


configuring view resolvers using either XML or Java-based configuration.
 Request Mapping allows you to define controller methods and map them to specific
HTTP request URLs, with options to handle HTTP methods, parameters, and path
variables.
 Spring MVC Form Tag Library simplifies form creation, binding form fields to
model objects, and handling form submissions and validation.
 Spring Validation provides support for server-side validation of form data using
annotations and custom validation logic, which can be integrated with Spring MVC
forms.

Introduction to Hibernate

Hibernate is an Object-Relational Mapping (ORM) framework for Java applications. It


simplifies database operations by mapping Java objects to database tables, making it easier to
interact with databases in a more object-oriented way. Hibernate handles low-level database
interactions and SQL operations, allowing developers to focus more on application logic
rather than database manipulation.

Key features of Hibernate:

 Object-Relational Mapping (ORM): Hibernate maps Java objects (POJOs) to


database tables and vice versa, automatically managing the transformation of data.
 Database Independence: It abstracts database operations, making it easier to switch
between different databases.
 Automatic Table Generation: Hibernate can automatically generate database tables
from Java objects (using annotations or XML configuration).
 Lazy Loading: It supports lazy loading, which improves performance by loading
related entities only when needed.

Benefits of Hibernate

1. Simplified Database Interaction:


o Hibernate eliminates the need to write SQL code for database operations. It
allows you to work with Java objects instead of dealing with relational tables
and SQL queries.
2. Portability:
o Hibernate is database-independent. You can switch databases with minimal
code changes because Hibernate abstracts the database-specific details.
3. Performance Optimization:
o Hibernate provides features like caching, lazy loading, and batch processing,
which can significantly improve the performance of applications.
4. Automatic Table Generation:
o With Hibernate, you don’t need to manually create database tables. It can
automatically generate the schema based on the entity class.
5. Support for Transactions:
o Hibernate integrates with Java Transaction API (JTA) to support declarative
transaction management, ensuring data consistency and integrity.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

6. Simplified CRUD Operations:


o Hibernate provides a simple API to perform Create, Read, Update, and Delete
operations on database records.

Explanation of hibernate.cfg.xml File

The hibernate.cfg.xml file is a configuration file used by Hibernate to specify various


settings for database connectivity, dialect, caching, and more. It is placed in the
src/main/resources directory.

1. Basic Structure of hibernate.cfg.xml:

xml
Copy code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate
Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property
name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</pr
operty>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_data
base</property>
<property
name="hibernate.connection.username">root</property>
<property
name="hibernate.connection.password">password</property>

<!-- JDBC connection pool settings -->


<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>

<!-- Specify dialect -->


<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property
>

<!-- Enable Hibernate's automatic session context management


-->
<property
name="hibernate.current_session_context_class">thread</property>

<!-- Echo all executed SQL to stdout -->


<property name="hibernate.show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->


<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Enable Hibernate's second-level cache -->


<property
name="hibernate.cache.use_second_level_cache">true</property>
</session-factory>
</hibernate-configuration>

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Key elements in the configuration:

o hibernate.connection.driver_class: Specifies the database driver.


o hibernate.connection.url: The JDBC URL for connecting to the database.
o hibernate.connection.username and hibernate.connection.password:
Database login credentials.
o hibernate.dialect: Specifies the dialect for the specific database you're
using.
o hibernate.show_sql: Whether to print SQL statements executed by
Hibernate.
o hibernate.hbm2ddl.auto: Controls how Hibernate manages schema updates
(e.g., update, create, validate).

The Relation Between Hibernate and JDBC

Hibernate is built on top of JDBC and serves as an abstraction layer over JDBC. Here’s how
Hibernate and JDBC relate:

1. JDBC:
oJDBC (Java Database Connectivity) is a low-level API for connecting to
relational databases and executing SQL queries.
o It requires developers to write SQL queries, manage connections, handle result
sets, and manage exceptions manually.
2. Hibernate:
o Hibernate abstracts away the complexities of JDBC by mapping Java objects
to database tables.
o Instead of writing SQL queries, you work with HQL (Hibernate Query
Language) or the Criteria API to interact with the database.
o Hibernate manages the connection pool, session management, and transaction
handling, simplifying database interaction.

Difference:

 JDBC: Works directly with SQL and database connections.


 Hibernate: Provides an object-oriented approach to interact with the database and
automatically generates SQL.

Program to Update Multiple Lines (Using HQL)

Hibernate Query Language (HQL) allows you to interact with the database using object-
oriented syntax rather than SQL. Here's how you can update multiple rows using HQL:

1. Example of HQL to Update Multiple Records:

Session session = HibernateUtil.getSessionFactory().openSession();


Transaction transaction = session.beginTransaction();

// Using HQL to update multiple records


String hql = "UPDATE Employee SET salary = :newSalary WHERE
department = :dept";
Query query = session.createQuery(hql);

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

query.setParameter("newSalary", 50000);
query.setParameter("dept", "HR");

int result = query.executeUpdate(); // Executes the update


System.out.println(result + " records updated.");

transaction.commit();
session.close();

In this example:

o HQL is used to update all employees in the "HR" department, setting their
salary to 50000.
o executeUpdate() performs the actual update.

CRUD Operations in Hibernate

Hibernate provides a simplified approach to perform Create, Read, Update, and Delete
operations using its Session object. Here's a basic example of each operation:

1. Create Operation (Insert a new record):

Session session = HibernateUtil.getSessionFactory().openSession();


Transaction transaction = session.beginTransaction();

Employee employee = new Employee();


employee.setName("John Doe");
employee.setSalary(45000);
employee.setDepartment("Finance");

session.save(employee); // Save the entity object


transaction.commit();
session.close();

2. Read Operation (Fetch a record):

Session session = HibernateUtil.getSessionFactory().openSession();


Employee employee = session.get(Employee.class, 1); // Fetch employee
with ID 1
System.out.println("Employee Name: " + employee.getName());
session.close();

3. Update Operation (Modify a record):

Session session = HibernateUtil.getSessionFactory().openSession();


Transaction transaction = session.beginTransaction();

Employee employee = session.get(Employee.class, 1); // Get employee


with ID 1
employee.setSalary(50000); // Update the salary
session.update(employee); // Save changes
transaction.commit();
session.close();

4. Delete Operation (Delete a record):

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Session session = HibernateUtil.getSessionFactory().openSession();


Transaction transaction = session.beginTransaction();

Employee employee = session.get(Employee.class, 1); // Get employee


with ID 1
session.delete(employee); // Delete the employee
transaction.commit();
session.close();

Summary

 Hibernate simplifies database operations by mapping Java objects to database tables,


making it easier to interact with the database through a higher-level API.
 Benefits of Hibernate include database independence, automatic schema generation,
caching, and simplified CRUD operations.
 The hibernate.cfg.xml file holds configuration properties for database
connectivity, dialect, and caching.
 Hibernate provides a higher-level abstraction over JDBC, allowing developers to
focus on objects rather than SQL.
 HQL (Hibernate Query Language) allows developers to write queries in an object-
oriented manner, and you can perform CRUD operations easily using Hibernate’s
Session API.

Introduction to Mapping in Hibernate

In Hibernate, mapping refers to the process of linking Java objects (or entities) to relational
database tables and columns. It involves defining how the properties of Java classes are
stored in the database tables. Mapping in Hibernate can be achieved using either annotations
or XML configuration.

The most common types of mappings in Hibernate are:

 One-to-One Mapping (1:1)


 Many-to-One Mapping (N:1)
 One-to-Many Mapping (1:N)
 Many-to-Many Mapping (N:M)

Each type of mapping defines the relationship between entities and how they are represented
in the database.

1. One-to-One (1:1) Mapping

A one-to-one (1:1) relationship means that one record in a table is associated with only one
record in another table. In Hibernate, this can be achieved using the @OneToOne annotation or
by using XML configuration.

Example of One-to-One Mapping

Entities:

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

 Employee has one Address (i.e., one employee can have one address).

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

@OneToOne
@JoinColumn(name = "address_id")
private Address address;

// Getters and setters


}

@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String street;
private String city;

// Getters and setters


}

In this example:

 @OneToOne: This annotation specifies the one-to-one relationship between Employee


and Address.
 @JoinColumn: Defines the foreign key column in the Employee table that references
the Address table.

Database Schema:

Employee Table:

id name address_id
1 John Doe 1

Address Table:

id street city
1 Elm St. NY

2. Many-to-One (N:1) Mapping

In a many-to-one (N:1) relationship, multiple instances of one entity are related to a single
instance of another entity. For example, many employees can belong to one department.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Example of Many-to-One Mapping

Entities:

 Employee has a Department (i.e., many employees can belong to one department).

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;

// Getters and setters


}

@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

// Getters and setters


}

In this example:

 @ManyToOne: Specifies the many-to-one relationship between Employee and


Department.
 @JoinColumn: Specifies the foreign key column (department_id) in the Employee
table referencing the Department table.

Database Schema:

Employee Table:

id name department_id
1 John Doe 1
2 Jane Doe 1

Department Table:

id name
1 HR
2 IT

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

3. One-to-Many (1:N) Mapping

A one-to-many (1:N) relationship is the inverse of a many-to-one (N:1) relationship. In this


case, one instance of an entity is related to many instances of another entity. For example,
one department can have many employees.

Example of One-to-Many Mapping

Entities:

 Department has many Employees (i.e., one department can have multiple
employees).

@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

@OneToMany(mappedBy = "department")
private Set<Employee> employees;

// Getters and setters


}

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;

// Getters and setters


}

In this example:

 @OneToMany: Specifies the one-to-many relationship between Department and


Employee.
 mappedBy: Defines the property in the Employee class that maintains the relationship.
 @ManyToOne: In the Employee class, this maps each employee to a single department.

Database Schema:

Employee Table:

id name department_id
1 John Doe 1

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

id name department_id
2 Jane Doe 1
3 Jim Beam 2

Department Table:

id name
1 HR
2 IT

4. Many-to-Many (N:M) Mapping

A many-to-many (N:M) relationship means that multiple instances of one entity can be
related to multiple instances of another entity. For example, a student can enroll in multiple
courses, and a course can have multiple students.

Example of Many-to-Many Mapping

Entities:

 Student and Course (i.e., many students can enroll in many courses).

@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

@ManyToMany
@JoinTable(
name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id")
)
private Set<Course> courses;

// Getters and setters


}

@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

@ManyToMany(mappedBy = "courses")
private Set<Student> students;

// Getters and setters


}

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

In this example:

 @ManyToMany: Specifies the many-to-many relationship between Student and


Course.
 @JoinTable: Creates a join table (student_course) to manage the many-to-many
relationship.
 mappedBy: In the Course class, it refers back to the courses field in the Student
class.

Database Schema:

Student Table:

id name
1 Alice
2 Bob

Course Table:

id name
1 Math
2 Science

Student_Course Table (Join Table):

student_id course_id
1 1
1 2
2 2

Summary of Mapping Types

 One-to-One (1:1): A record in one table is related to one record in another table (e.g.,
Employee and Address).
 Many-to-One (N:1): Many records in one table are related to one record in another
table (e.g., multiple Employee records to one Department).
 One-to-Many (1:N): One record in one table is related to many records in another
table (e.g., one Department to multiple Employees).
 Many-to-Many (N:M): Many records in one table are related to many records in
another table (e.g., Student and Course).

These mappings are essential in defining how data is related between Java objects and
database tables.

Garden City University

You might also like