Module-5 - Springs and Hibernates
Module-5 - Springs and Hibernates
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.
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.
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.
@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 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
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
}
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):
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.
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 {
@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.
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:
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>
<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">
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example")
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry
registry) {
registry.addViewController("/").setViewName("home");
}
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
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
}
}
3. Request Parameters:
o You can map parameters from the URL using @RequestParam or specify
request headers with @RequestHeader.
o Example:
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;
}
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.
2. Creating a Form:
o Use form:form to create a form, bind the form fields to a model object.
o Example:
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:
@Email
private String email;
}
@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:
@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 '@'");
}
}
}
Summary
Introduction to Hibernate
Benefits of Hibernate
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>
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:
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:
query.setParameter("newSalary", 50000);
query.setParameter("dept", "HR");
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.
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:
Summary
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.
Each type of mapping defines the relationship between entities and how they are represented
in the database.
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.
Entities:
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;
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String street;
private String city;
In this example:
Database Schema:
Employee Table:
id name address_id
1 John Doe 1
Address Table:
id street city
1 Elm St. NY
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.
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;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
In this example:
Database Schema:
Employee Table:
id name department_id
1 John Doe 1
2 Jane Doe 1
Department Table:
id name
1 HR
2 IT
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;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
In this example:
Database Schema:
Employee Table:
id name department_id
1 John Doe 1
id name department_id
2 Jane Doe 1
3 Jim Beam 2
Department Table:
id name
1 HR
2 IT
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.
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;
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(mappedBy = "courses")
private Set<Student> students;
In this example:
Database Schema:
Student Table:
id name
1 Alice
2 Bob
Course Table:
id name
1 Math
2 Science
student_id course_id
1 1
1 2
2 2
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.