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

Java Chapter 7

Chapter 7 discusses Object-Relational Mapping (ORM) as a solution to the mismatch between object-oriented programming and relational databases. It highlights the advantages of ORM, particularly Hibernate, which simplifies database interactions in Java applications. Additionally, the chapter covers various Java web frameworks, including Spring Boot, and introduces multithreading concepts and the life cycle of threads in Java.

Uploaded by

shibabhatta2063
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)
2 views21 pages

Java Chapter 7

Chapter 7 discusses Object-Relational Mapping (ORM) as a solution to the mismatch between object-oriented programming and relational databases. It highlights the advantages of ORM, particularly Hibernate, which simplifies database interactions in Java applications. Additionally, the chapter covers various Java web frameworks, including Spring Boot, and introduces multithreading concepts and the life cycle of threads in Java.

Uploaded by

shibabhatta2063
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

Chapter – 7

Advanced Topics in Java


Why Object Relational Mapping (ORM)?
When we work with an object – oriented system, there is a mismatch between the object model
and the relational database. RDBMS represent data in a tabular format whereas object – oriented
language, such as java or C# represent it as an interconnected graph of objects.
Consider the following java class with proper constructors and associated public function:
Consider the above objects are to be stored and retrieved into the following RDBMS table

First problem, what if we need to modify the design of our database after having developed a few
pages or our application? Second, loading and storing objects in a relational database exposes us
to the following mismatch problem:
 Granularity
Sometimes you will have an object model, which has more classes than the number of
corresponding tables in the database.
 Inheritance
RDBMSs do not define anything similar to inheritance, which is a natural paradigm in object –
oriented programming languages.
 Identity
An RDBMS defines exactly one notion of ‘sameness’: the primary key. Java, however, defines
both object identity (a==b) and object equality ([Link](b)).
 Association
Object – oriented languages represent associations using object refrences where an RDBMS
represents an association as a foreign key column.
 Navigation
The ways you access objects in java and in RDBMS are fundamentally different.

The Object – Relational Mapping (ORM) is the solution to handle all the above impedance
mismatch.

What is ORM?
ORM stands for Object – Relational Mapping (ORM) is a programming technique for converting
data between relational databases and object oriented programming languages such as java, C#
etc.
Advantages of ORM over JDBC
 Lets business code access objects rather than DB tables.
 Hides details of SQL queries from OO logic.
 Based on JDBC ‘under the hood’.
 No need to deal with the database implementation.
 Entities based on business concepts rather than database structure.
 Transaction management and automatic key generation
 Fast development of application.

ORM Solution
An ORM solution consists of the following entities:
 An API to perform basic CURD operation on objects of persistent classes.
 A language or API to specify queries that refer to classes and properties of classes.
 A configurable facility for specifying mapping metadata.
 A technique to interact with transactional object to perform dirty checking, lazy association
fetching and other optimization function.

Java ORM Frameworks


 Enterprise JavaBeans Entity Beans
 Java Data Objects
 Castor
 Toplink
 Spring DAO
 Hibernate etc.

Hibernate
Hibernate is an Object – Relational Mapping (ORM) solution for java. It is an open source
persistent framework created by Gavin King in 2001. It is powerful, high performance Object –
Relational Persistence and Query service for any data java application.
Hibernate maps java classes to database tables and from java data types to SQL data types and
relieves the developer from 95% of common data persistence related programming tasks.
Hibernate lies between traditional java objects and database server to handle all the work in
persisting those objects based on the appropriate O/R mechanism and patterns.
Hibernate Architecture

Hibernate has a layered architecture which helps the user to operate without having to know the
underlying APIs. Hibernate makes use of the database and configuration data to provide
persistence services (and persistent objects) to the application.
Hibernate uses various existing java APIs, like JDBC, Java Transaction API (JTA) and Java
Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of
functionality common to relational databases, allowing almost any database with a JDBC driver
to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE
application servers.
Following section gives brief description of each of the class object involved in Hibernate
Application Architecture.
Configuration Object
The configuration object is the first Hibernate object you create in any Hibernate application. It is
created only once during application initialization. The configuration object provides two keys
components
 Database Connection: This is handled through one or more configuration files supported
by Hibernate. These files are [Link] and [Link].
 Class Mapping Setup: This component creates the connection between the java classes
and database tables.
SessionFactory Object
SessionFactory Object configures Hibernate for the application using the supplied configuration
file and allows for a session object to be instantiated. The sessionFactory is a thread safe object
and used by all the threads of an application. The SessionFactory is a heavyweight object; it is
usually created suring application startup and kept for later use.
Session Object
A session is used to get a physical connection with a database. The session object is lightweight
and designed to be instantiated wach time an interaction is needed with the database. Persistent
objects are saved and retrieved through a Session object. The session objects should not be kept
open for a long time because they are not usually thread safe and they should be created and
destroyed them as needed.
Transaction Object
A transaction represents a unit of work with the database and most of the RDBMS supports
transaction functionality. Transactions in Hibernate are handled by an underlying transaction
manager and transaction (From JDBC or JTA). This is an optional object and Hibernate
applications may choose not to use this interface, instead managing transactions in their own
application code.
Query Object
Query object use SQL or Hibernate Query Language (HQL) string to retrieve data from the
database and create objects. A query instance is used to bind query parameters, limit the number
of results returned by the query and finally to execute the query.
Criteria Object
Criteria objects are used to create and execute object oriented criteria queries to retrieve objects.

Advantage of Hibernate
 Hibernate takes care of mapping java classes to database table using XML files and without
writing any line of code.
 Provides simple APIs for storing and retrieving java objects directly to and from the database.
 If there is change in the database or in any table, then you need to change the XML file
properties only.
 Abstracts away the unfamiliar SQL types and provides a way to work around familiar java
objects.
 Hibernate does not require an application server to operate. Manipulates Complex associations
of objects of your database.
 Minimizes database access with smart fetching strategies.
 Provides simple querying of data.

Hibernate Mapping files


Property Mapping

Association Mapping
Java Web Framework
1. Spring
Spring is a powerful, lightweight, and most popular framework which makes Java quicker,
easier, and safer to use. This framework is very popular among developers for its speed,
simplicity, and productivity which helps to create enterprise-level web applications with
complete ease. Spring MVC and Spring Boot made Java modern, reactive, and cloud-ready to
build high-performance complex web applications hence used by many tech giants, including
Netflix, Amazon, Google, Microsoft, etc.
 Using Spring's flexible and comprehensive third-party libraries you can build any web
application you can imagine.
 Start a new Spring project in seconds, with, fast startup, fast shutdown, and optimized
execution by default.
 Spring provides a lightweight container that can be triggered without a web server or
application server.
 It provides backward compatibility and easy testability of your project.
 It supports JDBC which improves productivity and reduces error as much as possible
 It supports modularity and both XML and annotation-based configuration
 Spring Boot has a huge ecosystem and community with extensive documentation and
multiple Spring tutorials
2. Grails
It is a dynamic full-stack Java framework based on the MVC design pattern. which is easy to
learn and most suitable for beginners. Grails is an Object Oriented Language that enhances
developer productivity. While written in Groovy it can run on the Java platform and is perfectly
compatible with Java syntax.
 Easy to Create tags for the View,
 built-in support for RESTFUL APIs.
 you can mix Groovy and Java using Grails,
 best suitable for Rapid Development,
 configuration features are dynamic, no need to restart the server

3. Google Web Toolkit (GWT)


It is a very popular open-source Java framework used by a large number of developers around
the world for building and optimizing complex browser-based applications. This framework is
used for the productive development of high-performance complex web applications without
being an expert in front-end technologies like JavaScript or responsive design. It converts Java
code into JavaScript code which is a remarkable feature of GWT. Popular Google applications
like AdSense and AdWords are written and using this framework.
 Google APIs are vastly used in GWT applications.
 Open-source and Developer-friendly.
 Easily create beautiful UIs without vast knowledge in front-end scripting languages.
 Create optimized web applications that are easy to debug.
 Compiles the Java source code into JavaScript files that can run on all major browsers.
4. Struts
It is a very useful framework, an open-source MVC framework for creating modern enterprise-
level Java web applications that favor convention over configuration and reduce overall
development time. It comes with plugins to support REST, AJAX and JSON and can be easily
integrated with other Java frameworks like Spring and Hibernate.
 Super Flexible and beginner-friendly,
 Reliable, based on MVC design pattern.
 Integration with REST, JSON, and AJAX.
 Creative themes and templates make development tasks faster.
 Extend capabilities for complex development,
 Reduced development time and Effort, makes dev easier and fun.

5. Java Server Faces (JSF)


It is quite similar to Struts, a free web application developed framework, maintained by Oracle
technology which simplifies building user interfaces for Server-side applications by assembling
reusable UI components on a page. JSF is a component-based MVC framework that encapsulates
various client-side technologies and focuses more on the presentation layer to allow web
developers to create UI simply by just drag and dropping.
 Rich libraries and reusable UI components,
 Easy front-end tools to use without too much coding,
 Jsf helps to improve productivity and consistency,
 Enrich the user experience by adding Ajax events for validations and method invocations.
 It provides an API to represent and manage UI components and instead of using Java, JSF
uses XML for view handling.

6. Hibernate
A stable, lightweight ORM Java framework that can easily communicate with any database and
is more convenient when working with multiple databases. Working with Hibernate is fun using
powerful APIs and several useful tools like Mapping Editor, Wizards, and Reverse Engineering.
Many big companies including Platform, DAILY HOTEL, IBM, and Dell use Hibernate in their
tech stacks,
 Light-weight and easy to scale up, modify, and configure.
 Complex data manipulation with less coding.
 High productivity and portability,
 Used for RDBMS as well as the NoSQL database.
 Awesome Command-line tools and IDE plugins to make your experience pleasant.

Session Object
A session is used to get a physical connection with a database. The session object is lightweight
and designed to be instantiated wach time an interaction is needed with the database. Persistent
objects are saved and retrieved through a Session object. The session objects should not be kept
open for a long time because they are not usually thread safe and they should be created and
destroyed them as needed.

Introduction to Spring Boot


Spring is widely used for creating scalable application. For web applications, Spring provides
Spring MVC, a commonly used module for building robust web applications. The major drawback
of traditional Spring projects is that configuration can be time – consuming and overwhelming for
new developers. Making an application production – ready requires significant effort.
The solution to this is “Spring Boot”. Spring Boot is built on the top of the Spring Framework and
includes all Spring features while simplifying configuration. It has become a developer favorite
due to its rapid development capabilities, allowing developers to focus on business logic instead
of struggling with configurations.
Spring Boot is a microservice – based framework that enables quick development of production –
ready applications. A prerequisite for learning Spring Boot is a basic understanding of the Spring
Framework.

Features of Spring Boot


1. Auto – Configuration
Spring Boot eliminates the need for heavy XML configuration, which is common in
traditional Spring MVC projects. Instead, everything is auto-configured. Developers only need
to add the appropriate configuration to utilize specific functionalities. For example, if we want
to use Hibernate (ORM) we can simply add the @Table annotation to our model/entity class and
the @Column annotation to map it to database tables and columns. By 2025, Spring Boot's auto-
configuration has become even smarter, utilizing AI-driven optimizations to further reduce
manual setup.
2. Easy Maintenance and Creation of REST Endpoints
Creating REST APIs is incredibly easy in Spring Boot. With annotations
like @RestController and @RequestMapping, developers can quickly define endpoints. By
2025, Spring Boot has introduced even more advanced annotations
like @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping, making REST
API development more intuitive and efficient
3. Embedded Tomcat Server
Unlike traditional Spring MVC projects, where you need to manually install and configure a
Tomcat server, Spring Boot comes with an Embedded Tomcat Server. This allows applications
to be hosted directly without additional setup. By 2025, Spring Boot also supports other
embedded servers like Jetty and Undertow, giving developers more flexibility based on their
application requirements.
4. Easy Deployment
Spring Boot simplifies deployment by allowing applications to be packaged
as JAR or WAR files. These files can be directly deployed to a Tomcat server or cloud
environment. By 2025, Spring Boot has enhanced its deployment capabilities with seamless
integration into Kubernetes and Docker, making it easier to deploy and scale applications in
cloud-native environments.
5. Microservice – Based Architecture
Spring Boot is designed for microservices, which are small, independent modules that focus on
a single functionality. For example, in a hospital management system, you might have separate
services for patient registration, billing, and database management. By 2025, Spring Boot has
further optimized its microservice support with features. In a monolithic system, all features are
bundled into a single codebase, making it difficult to maintain and scale. In a microservice-based
system, each feature is divided into smaller, independent services. This modular approach makes
the system easier to maintain, debug, and deploy. Each service can be built using different
technologies suited to its specific requirements.
Spring Boot Architecture
To understand the architecture of Spring Boot, Let’s examine its different layers and components.
Layers in Spring Boot
Spring Boot follows a layered architecture with the following key layers.
Client Layer
 This represents the external system or user that interacts with the application by sending
HTTPs requests.
Controller Layer (Presentation Layer)
 Handles incoming HTTP requests from the client.
 Processes the request and sends a response.
 Delegates business logic processing to the service layer.
Service Layer (Business Logic Layer)
 Contains business logic and service classes.
 Communicates with the repository layer to fetch or update data.
 Uses Dependency injection to get required repository services.
Repository Layer (Data Access Layer)
 Handles CURD (create, read, update, delete) operation on the database.
 Extends Spring Data JPA or other persistence mechanisms.
Model Layer (Entity Layer)
 Represents database entities and domain models.
 Maps to tables in the database using JPA/Spring Data
Database Layer
 The actual database that stores application data.
 Spring Boot interacts with it through JPA / Spring Data

Multithreading
A thread is a single sequential flow of control within a program. Threads are also called light
weight processes. A program that has many threads running concurrently is called multithreading.
Java multithreading program is platform dependent. Thus, a multithreaded application could
behave differently on different java implementations.
By definition multitasking is when multiple processes share common processing resources such as
a CPU. Multi-threading extends the idea of multitasking into applications where we can subdivide
specific operations within a single application into individual threads. Each of the threads can run
in parallel. The OS divides processing time not only among different applications, but also among
each thread within an application. Multi-threading enable us to write in a way where multiple
activities can proceed concurrently in the same program.

Transition Diagram or State Diagram or Life Cycle of a Thread


A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle
in java new, runnable, non-runnable and terminated. There is no running state. But for better
understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. Newborn
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated or Dead
1. New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method. It remains in this state until the program starts the thread. It is also referred to as a
born thread.
2. Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread. A thread in this state is considered to be executing its task.
3. Running
The thread is in running state if the thread scheduler has selected it. Sometimes, a thread transitions
to the waiting state while the thread waits for another thread to perform a task. A thread transitions
back to the runnable state only when another thread signals the waiting thread to continue
executing.
4. Non – Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run. A runnable thread
can enter the timed waiting state for a specified interval of time. This happens when the thread
performs some kind of input output action or communicating between the Threads. A thread in this
state transitions back to the runnable state when that time interval expires or when the event it is
waiting for occurs.
5. Terminated or Dead
A runnable thread enters the terminated state when it completes its task or otherwise terminates.

How to create a thread?


Threads are implemented in the form of objects that contain the method called run() method. The
run() method should be invoked by an object of the concerned thread. This can be achieved by
creating the thread and initiating it with the help of another thread method called start() method.
The run() method can be written in two ways.
• By extending Thread class
• By implementing Runnable Interface
Thread Creation by extending the Thread class
We create a class that extends the [Link] class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object of
our new class and call start() method to start the execution of a thread. Start() invokes the run()
method on the Thread object.
Thread Creation by implementing the Runnable Interface
Synchronization
At times when more than one thread try to access a shared resource, we need to ensure that
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization. The synchronization keyword in java creates a block of code referred to as critical
section.
Synchronized(object)
{
// statement to be synchronized
}
Every java object with a critical section of code gets a lock associated with the object. To enter
critical section a thread need to obtain the corresponding object’s [Link] we do not use
synchronization, an let two or more threads access a shared resource at the same time, it will
lead to distorted results.
Synchronization is broadly classified into two categories:
1. Method level synchronization
2. Block level synchronization

1. Method level synchronization


Using synchronized methods is a way to accomplish synchronization.
Example
public synchronized void run()
{
// same resource
}
[Link]();
[Link]();
[Link]();
2. Block level synchronization
If we have to synchronize access to an object of a class or we only want a part of a method to be
synchronized to an object then we can use synchronized block for it.
Example:
public void run()
{
synchronized(this)
{
// same resource
}
}
[Link]();
[Link]();
[Link]();

When we use synchronized keyword with a method, it acquires a lock in the object for the whole
method. It means that no other thread can use any synchronized method until the current thread,
which has invoked its synchronized method has finished its execution.
Synchronization block acquires a lock in the object only between parentheses after the
synchronized keyword. This means that no other thread can acquire a lock on the locked object
until the synchronized block exist. But other threads can access the rest of the code of the
method.
Example
Thread Deadlock
Deadlock is a situation of complete lock, when no thread can complete its execution because lack
of resources. In the below picture, thread is holding a resource R1, and need another resource
R2 to finish execution, but R2 is locked by thread 2, which needs R3, which in turn is locked by
thread 3. hence none of them can finish and are stuck in a deadlock.’

Thread Pooling
A thread pool is a collection of pre – initialized threads. The general plan behind a thread pool is
to form variety of threads at method startup and place them into a pool, wherever they sit and
expect work. Once a server receives a call for participation, it awakens a thread from this pool, if
one is available and passes it the request for service. Once the thread completes its service, it
returns to the pool and awaits a lot off work. If the pool contains no accessible thread, the server
waits till one become free.
Why use thread pools in java
 It saves time as a result of there is no need to produce new thread.
 It utilized in servlet and JSP where ever instrumentality creates a thread pool to method the request.

Creating thread pools in java

Java provides a [Link] class provides couple of methods to create a thread pools.

Following are methods to create a thread pools

a. public static ExecutorService newCachedThreadPool()


b. public static ExecutorService newFixedThreadPool(int n Threads)
c. public static ScheduledExecutorService newScheduleThreadPool(int corePoolSize)
d. public static ExecutorService newWorkStealingPool()

You might also like