Java Notes
Java Notes
MVC is a model view controller software design pattern used for developing user interfaces that
separates an application into three interconnected components. This separation helps in organizing
code more effectively and makes it easier to manage and scale.
The Components
1. Model
1.1 it is responsible for the application’s data, business logic, and rules
1.2 it communicates directly with the database and performs operations on the data
` 1.3. it doesn’t depend on the user interface, it represents the internal state of the application
2. View
2.1 The view is responsible for presenting the data to the user
2.2 It listens to the changes in the Model and updates the UI accordingly
2.3 it contains the layout, design and structure of how the data will be shown but doesn’t
process the data itself
3. Controller
3.1 The controller acts as an intermediary between the Model and the View
3.2 it listens to user input from the View, processes it, and then updates the View.
3.3 The controller handles user requests and triggers the necessary actions in the Model or
updates the View
Example
1. Model
1.1 Presents the Book object in the system. It interacts with the DB to retrieve and store data
about the books (title, name, author, availability)
1.2 Example: A method to fetch all books from the DB or add a new book
2. View
2.1 The web page (HTML, CSS, JavaScript) that displays the list of books to the user.
2.2 Example: The page will list all books with their details like title and availability. If a user
wants to add a new book, the view will provide an input form.
3. Controller
3.1 Handles the user actions from the View (button clicks or forms submission) and updates
the Model accordingly
3.2 Example: when a user submits a from to add a new book, the Controller will take the
data, pass it to the Model, which then stores the book in the DB. After this, the Controller
might update the View to show the updated list of books.
1. User interacts with the View (e.g., clicks a button or submits a form).
2. The controller takes the input, processes it, and might make changes to the Model (e.g.,
adding a book or fetching book data).
4. The Controller updates the View (or redirects to another page), and the user sees the
updated UI
Advantages
1. Separation of Code: MVC separates the logic into three distinct parts: Model, View, and
Controller. This makes the codebase easier to understand, maintain, and scale.
2. Maintainability: Since the application logic is separated into components, developers can
work on each part independently. For instance, if you need to change how the data is
displayed, you can work on the View without affecting the Model or Controller.
3. Reusability: The model can be reused across different views. For example, the same
Model might serve multiple views for different platforms (web, mobile, desktop)
4. Testability: With MVC, each component can be tested individually. You can test the
Model’s business logic separately from the UI or the user interaction.
5. Flexibility: MVC allows for different views of the same data. You can modify how the data
is presented without changing the core logic of the application.
6. Scalability: As applications grow, you can extend or replace components (Model, View,
Controller) without impacting the rest of the application. For example, you can change the
database logic in Model without affecting the View
To integrate Spring and Hibernate, necessary libraries must be added to your project.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.x.x</version>
</dependency>
Step 2: Configure Hibernate SessionFactory in Spring
The SessionFactory is the main interface in Hibernate that allows you to interact with the database.
You need to configure it in the Spring context to establish the connection between Spring and
Hibernate. Create a Spring Configuration file (e.g., applicationContext.xlm) to define the
SessionFactory
Next, configure a DataSource to manage the database connection. This can be done using a
traditional JDBC DriverManagerDataSource or using a connection pool such as HikariCP.
Create a java model class that will represent data you want to persist to the database. These classes
should be annotated with Hibernate annotations.
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@Id
The DAO layer is responsible for abstracting the data access logic. You can use Hibernates Session API
to interact with the database.
}
Step 7: Create Service Layer to Handle Business Logic
The service layer contains the business logic and interacts with the DAO layer. The service can be
annotated with @Service and @Transactional to handle transactions automatically.
@Service
@Autowired
@Transactional
bookDao.saveBook(book);
@Transactional(readOnly = true)
return bookDao.getBook(id);
Now, you can create a main class or a Spring Boot application to test the integration.
Conclusion
Integrating Spring Framework with Hibernate enables you to combine the power of dependency
injection and transaction management from Spring with the ORM capabilities of Hibernate. The
integration simplifies database operations and improves maintainability and scalability of enterprise
applications.
Hibernate maps Java objects to database tables automatically, reducing the need to write
SQL queries.
2. Loose Coupling
Spring’s Dependency Injection (DI) makes components independent and easier to manage,
test, and extend.
3. Declarative Transaction Management
4. Better Testability
Spring and Hibernate together make it easier to test database interactions by allowing mock
objects and in-memory databases.
5. Simplified Configuration
Spring centralizes the configuration (like database connections) in one place, reducing
complexity.
6. Improved Performance
Hibernate’s caching and lazy loading help in improving performance by reducing unnecessary
database calls.
You can easily integrate with other Spring features like AOP (Aspect-Oriented Programming)
for logging, security, and more.
8. Error Handling
Spring translates Hibernate exceptions into more meaningful ones, making error handling
simpler.
9. Faster Development
Spring and Hibernate reduce the amount of boilerplate code you need to write, speeding up
development.
10. Flexibility
You can configure different data sources or add custom Hibernate settings with ease, making
the application adaptable to various needs.
The HibernateTemplate class is part of the Spring Framework and provides a simplified approach to
interacting with Hibernate. It handles the session management and exception translation, so
developers don't have to deal with Hibernate-specific boilerplate code. HibernateTemplate makes it
easier to perform common database operations like saving, updating, deleting, and querying objects.
Methods
1. save()
Example: hibernateTemplate.save(book);
2. update()
Example: hibernateTemplate.update(book);
3. saveOrUpdate()
Purpose: Saves a new entity or updates an existing entity based on its identifier (primary
key).
Example: hibernateTemplate.saveOrUpdate(book);
4. delete()
Example: hibernateTemplate.delete(book);
5. get()
Purpose: Retrieves an entity by its identifier (primary key). Returns null if the entity does not
exist.
6. load()
Purpose: Loads an entity by its identifier (primary key). Throws an exception if the entity is
not found (difference from get() which returns null).
7. batchUpdate()
8. clear()
Purpose: Clears the session cache, which can help to avoid memory issues when dealing with
large data sets.
Example: hibernateTemplate.clear();
9. flush()
Purpose: Forces Hibernate to flush any changes to the database (e.g., updates, deletes) that
are still pending.
Example: hibernateTemplate.flush();
Differentiate Spring and Hibernate
1. Purpose
Spring: A broad framework that helps with building entire applications. It provides tools for
managing objects, handling transactions, security, and more.
2. Main Functionality
Spring: Manages application flow, transactions, and integrates with other technologies (like
Hibernate, databases, messaging, etc.).
Hibernate: Focuses on mapping Java objects to database tables (ORM), making database
operations easier.
3. Scope
Spring: Covers the whole application, including web development, security, and more.
4. Transaction Management
5. Learning Curve
6. Integration
Hibernate: Primarily works on its own for database tasks but can be integrated with Spring
for better session and transaction management.