0% found this document useful (0 votes)
15 views

Java - 2 Meet Ref

Uploaded by

nandish4647
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)
15 views

Java - 2 Meet Ref

Uploaded by

nandish4647
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/ 18

UNIT – 2 JAVA DATABASE CONNECTIVITY

2.1 INTRODUCTION TO JDBC :


JDBC (Java Database Connectivity) is a Java API used to run SQL commands. It is the standard way
for Java programs to connect to databases. JDBC is made up of classes and interfaces written in Java.
It is easy to send SQL statements to virtually any relational database. Combination of Java and JDBC
makes it possible for a programmer to "write it once and run it anywhere".

Over time, JDBC has improved to offer better performance, security, and ease of use. It continues to
be the main tool for Java developers to connect and work with databases in various applications.
2.2 JDBC ARCHITECTURE :
The JDBC (Java Database Connectivity) architecture follows a layered approach to create a common
interface for connecting Java applications to different databases. It works on a client-server model: the
Java application acts as the client, and the database server is the server. The driver translates the JDBC
API calls from Java applications into commands that the specific database can understand and
execute.

The JDBC Architecture consists of two layers :


- The JDBC API : This connects the application to the JDBC Manager.
- Driver manager and Database Drivers : The JDBC API uses these to connect transparently to various
databases.

The JDBC API layer acts as an abstraction layer, hiding the specific details of different databases.
This makes it easier to create applications that can work with any database without needing changes
in the code for each type of database.
- It includes the following key components :
- Connection
- Statement
- PreparedStatement
- CallableStatement
- ResultSet
- DriverManager

- The JDBC Driver APl, manages the connection between the JDBC Manager and the drivers.
- The JDBC Driver layer, consists of the various JDBC drivers that connect Java applications to
specific databases (DBMS).
- JDBC drivers, implement the JDBC API interfaces and provide the necessary functionality to
interact with the database. The driver manager can support multiple drivers, allowing connections to
various databases at the same time.

- There are four types of JDBC drivers. Each JDBC driver implements specific mechanism to handle
connections, query execution, result retrieval, and specific database tasks.

- The JDBC Driver layer serves as a bridge between the Java application and database, converting
JDBC API commands into specific actions and protocols that the database understands.
2.2.1 TWO TIER JDBC ARCHITECTURE :
Two models for database access are supported by the JDBC API.
1. Two-tier model
2. Three-tier model

THE TWO-TIER MODEL :


- In the Two-Tier JDBC Architecture, also known as the Client/Server Architecture, the Java
application directly connects to the database server.
- The key components in this architecture are the Java application (client) and the database server.
- The Java application handles both the user interface and the data access.
- The connects directly to the database server using a JDBC driver.
- All SQL queries and database updates are performed by the Java application.
- This architecture is suitable for small-scale applications where the database server is directly
accessible from the client-side application.
THREE TIER ARCHITECTURE :
In the Three-Tier JDBC Architecture, also called the Client/Server/Middleware Architecture, there is
an extra layer called middleware or an application server between the Java application (client) and the
database server.

- The Three-Tier JDBC Architecture has three layers: the presentation layer, the application layer
(middleware), and the data layer (database server).
- The presentation layer manages the user interface and user interactions.
- The application layer (middleware) acts as an intermediate layer between the Java application and
the database server.
- The Java application sends requests to the middleware, which processes the requests and interacts
with the database server using JDBC.
- The middleware adds features like connection pooling, security, load balancing, and caching.
- This architecture helps to separate different tasks. It enables multiple Java applications to connect to
the same middleware layer and share resources efficiently.
- It also improves database connection management, reducing the overhead of creating connections
for each request.
JDBC ADVANTAGES :
Platform Independence :
- JDBC is a Java-based technology, making it platform-independent. It can be used on any operating
system that supports the Java platform.

Database Connectivity :
- JDBC provides a standard set of interfaces and classes for connecting to various databases, allowing
seamless interaction with the database systems.

Database Vendor Support :


JDBC supports a wide range of database vendors, allowing developers to connect and interact with
different databases using a unified API.

Performance :
- JDBC offers efficient and high-performance database operations by providing direct interaction with
the database, avoiding extra layers or protocols.

SQL Compatibility :
- JDBC supports the use of standard SQL statements, enabling developers to execute SQL queries,
updates, and stored procedures across different databases with minimal modifications.

JDBC DISADVANTAGES :
Manual Resource Management :
- JDBC requires developers to manually manage database resources, such as opening and closing
connections, statements, and result sets. This can be error-prone and tedious.

Boilerplate Code :
- JDBC often involves writing a lot of repetitive code for common tasks like connection management,
result set processing, and exception handling.

Database-specific Code :
- While JDBC offers a common API, certain operations may require database-specific code, reducing
portability and increasing development effort.

Lack of Object-Relational Mapping (ORM) :


- JDBC does not have built-in support for object-relational mapping, so developers must manually
map database objects to Java objects, which can be complex and time-consuming for large projects.

Limited Query Capabilities :


- JDBC mainly supports basic SQL operations and lacks advanced query features, making it less
suitable for complex data retrieval and manipulation tasks.
2.3 JDBC COMPONENTS :

The JDBC architecture consists of the following key components :


1. JDBC API
- The JDBC API provides a set of Java interfaces and classes that define the standard methods for
connecting to databases.
- It includes interfaces such as Connection, Statement, PreparedStatement, CallableStatement, and
ResultSet, which are used for different tasks when working with a database.

2. JDBC Drivers
- JDBC drivers are software tools that connect a Java application to a specific database management
system (DBMS).
- JDBC drivers implement the JDBC API and provide the necessary functions needed to interact with
the database.
- There are four types of JDBC drivers:
- Type-1 : JDBC-ODBC Bridge drivers uses ODBC interface to connect to the DBMS.
- Type-2 : Native API-Partly Java drivers use native libraries to interact with the DBMS.
- Type-3 : Network Protocol drivers connect to a middleware server, which then communicates with
the DBMS.
- Type-4 : Pure Java drivers directly connect to the DBMS without requiring additional native
libraries.

3. JDBC Manager
- The JDBC Manager manages how the Java application interacts with JDBC drivers.
- It handles tasks like loading the correct JDBC driver, establishing and closing database connections,
and managing transactions.
- The JDBC Manager makes sure that the appropriate driver is used based on the JDBC API calls
made by the application.

4. DataSource
- A DataSource is an object that provides a standard way to get database connections.
- It can be set up with details like the database URL, username, password, and other parameters.
- DataSource can be managed by an application server or a connection pooling system to handle and
reuse database connections efficiently.

5. Database
- The database is the storage system where the data is saved and accessed.
- The JDBC architecture allows Java applications to connect with different databases, such as
MySQL, Oracle, or PostgreSQL.

APPLICATION mathi API CALL thy..


a API CALL.. JDBC MANAGER jode jay..
JDBC MANAGER thi.. JDBC DRIVER jode jay..
JDBC API :
The Java programming language provides a universal data access through the JDBC API. JDBC
allows you to access almost any data source, including relational databases, spreadsheets and files. It
serves as a common base for developing tools and other data access interfaces.

The JDBC API has two packages:


1. java.sql
2. javax.sql

Java Database Connectivity (JDBC) API:


- General API (Application programming interface) for Java program to connect to a database
- Database providers (IBM, Oracle, etc.) provide drivers
- Driver : specific implementation of the API used to interact with a particular database

- Support for
a) Statement
b) Prepared Statement
c) Callable Statement (stored procedures)
d) Common Java data types (Integer, Double, java.sql.Date)

- The javax.sql and java.sql are the main packages for JDBC 4.0. They provide essential classes for
working with data sources The new features in these packages include changes in the following areas :
- Automatic database driver loading.
- Improved exception handling.
- Enhanced BLOB/CLOB functionality.
- Connection and statement interface enhancements.
- Support for National character set.
- SQL ROWID access.
- SQL 2003 XML data type support.
- Annotations.
CRUD Operations :
Creating, reading, updating, and deleting data in a database is a common task in many applications,
and JDBC (Java Database Connectivity) is a Java API that allows you to perform these operations. In
this guide, we will go through the steps of setting up a simple CRUD (create, read, update, delete)
operation using JDBC.

1. Connect to the database


- The first step is to establish a connection with database.
- You can do this by loading the JDBC driver and creating a connection object.

2. Create a new record


- Once you have a connection to the database, you can use the connection object to create a new
record in the database.
- To do this, you will need to use an SQL INSERT statement and execute it using the connection
object

3. Read a record
- To read a record from the database, you will need to use an SQL SELECT statement and execute it
using the connection object.
- Retrieve the results using a ResultSet object.

4. Update a record
- To update a record in the database, you will need to use an SQL UPDATE statement and execute it
using the connection object.

5. Delete a record
- To delete a record from the database, you will need to use an SQL DELETE statement and execute it
using the connection object

Summary :
CRUD operations in Java can be easily performed using JDBC. With a few simple steps, you can
connect to a database, create new records, read existing records, update records, and delete records.
This allows you to easily manage your data and maintain the integrity of your application.
JDBC Drivers :
- JDBC is an Java API that specifies how a client can access tabular data, especially relational
databases. It's part of the Java Standard Edition platform by Oracle Corporation. It acts as a middle
layer between Java applications and databases.
- The JDBC classes are contained in the Java Package java.sql and javax.sql.

- JDBC helps you to write Java applications that manage these three programming activities :
1. Connect to a data source, like a database.
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query

- JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
converts requests from Java programs into a format that DBMS can understand. There are 4 types of
JDBC drivers:

Types of JDBC Drivers


There are four different types of JDBC drivers:
1. Type 1: JDBC - ODBC bridge driver
2. Type 2: Java - Native code driver
3. Type 3: Network - Protocol driver (Middleware driver)
4. Type 4: Database - Protocol driver (Pure Java driver)
(i) JDBC – ODBC Bridge
- Uses ODBC API to connect to database.
- Provides a bridge between the JDBC API and ODBC API.
- Converts JDBC method calls into ODBC function calls.
- Relies on an existing ODBC driver for database connections.
- Easy to install and configure.
- The ODBC bridge driver is needed to be installed in individual client machines.
- It isn’t written in java, that’s why it isn’t a portable driver.
- Type-1 driver is also called Universal driver because it can be used to connect to any of the
databases.

Advantages :
- Easy to use.
- Can be easily connect to any database.

Disadvantages :
- Performance degraded because JDBC calls converts into ODBC function calls.
- The ODBC driver requires installation on the client machine.
(ii) Native – API Driver
- Converts JDBC API calls into database-specific calls using native libraries.
- Does not depend on ODBC.
- Direct access to database- specific features and optimizations.
- Better performance compared to Type 1 drivers
- It is not written entirely in java.

Advantage :
- Performance upgrades than JDBC-ODBC bridge driver.

Disadvantages :
- The Native driver requires installation on the each client machine.
- The Vendor client library requires installation on client machine.
(iii) Network – Protocol Driver (Middleware Driver)
- Communicates with a middleware server using a database independent network protocol.
- The middleware server then communicates with a actual database.
- Provides network transparency and allows supports remote database access.
- Platform-independent.
- It is fully written in java.

Advantage :
- No need for client-side libraries; the application server handles tasks such as auditing, load
balancing, and logging.

Disadvantages :
- Requires network support on the client machine.
- Needs database-specific coding for the middle tier.
- Maintenance can be costly due to the need for database-specific coding in the middle tier.
(iv) Database – Protocol Driver (Pure Java Driver)
- Directly translates JDBC API calls into database- specific network protocol calls.
- No dependency on external libraries or middleware.
- Suitable for most databases and widely used in production environments.
- Platform-independent and does not require additional installations.
- Provides good performance as it communicates directly with the database.
- Known as a Thin driver because it converts JDBC calls directly into the vendor-specific database
protocol and is written entirely in Java.

Advantages :
- Better performance than all other drivers.
- No software is required on the client side or server side.

Disadvantage :
- Drivers depends on the Database.
ORM MODEL :
- Object-Relational Mapping (ORM) is a technique that bridges the gap between object-oriented
programming (OOP) languages and relational databases. ORM acts as a middle layer between your
OOP code and the database. It helps you interact with the database using objects rather than writing
raw SQL queries.
- Instead of writing complex SQL queries, ORM tools handle the conversion between Java objects and
database tables, making CRUD (Create, Read, Update, Delete) operations more intuitive and less
error-prone.
- In an ORM model, the database interactions are managed through an ORM framework, which
translates OOP operations into SQL queries. This abstraction reduces the amount of boilerplate code
and simplifies the process of managing database connections and transactions.

Key Concepts in ORM :


1) Entities :
- Entities are Java classes that represent objects you want to save in the database. Each entity typically
matches to a table in the database. For example, a User class might map to a users table.

2) Annotations :
- Hibernate uses annotations to define the mapping between Java classes and database tables.
Annotations like @Entity, @Table, and @Column shows how Java classes and their properties are
mapped to the database schema.

3) Primary Keys :
- Each entity has a primary key that uniquely identifies each record in the table. Hibernate supports
various types of primary keys, including single-column primary keys, composite primary keys, and
generated (auto-incremented) primary keys.

5) Associations :
- Associations define the relationships between entities. Hibernate supports different types of
associations :
- One-to-One : One entity is associated with another single entity.
- One-to-Many : One entity is associated with multiple entities.
- Many-to-One : Multiple entities are associated with a single entity.
- Many-to-Many : Multiple entities are associated with multiple entities.
- These associations are mapped using annotations like @OneToOne, @OneToMany,
@ManyToOne, and @ManyToMany.

6) Cascading Operations :
- Cascading allows you to perform certain operations such as insert, update, delete on a parent entity,
and these actions are automatically applied to its related child entities. Hibernate provides cascading
options such as CascadeType.ALL, CascadeType.PERSIST, and CascadeType.MERGE to manage
these behaviors.

7) Inheritance Mapping :
- Hibernate supports different strategies for mapping inheritance hierarchies:
- Single Table : All classes in the hierarchy are mapped to a single table.
- Joined Table : Each class in the hierarchy is mapped to its own table, with relationships
maintained through joins.
- Table Per Class : Each class in the hierarchy has its own table, with no joins required.
These strategies determine how the inheritance structure is represented in the database.
ORM TOOLS :
An ORM tool is software designed to help OOP developers interact with relational databases. So
instead of creating your own ORM software from scratch, you can make use of these tools.
Most OOP languages have a variety of ORM tools that you can choose from.

Popular ORM Tools for Java


1. Hibernate :
- Hibernate helps developers use OOP concepts like inheritance and associations to manage database
data. It is known for being fast and scalable.

2. Apache OpenJPA :
- Apache OpenJPA is a Java tool that helps with data persistence. It can work as a standalone system
for managing plain Java objects.

3. EclipseLink :
- EclipseLink is an open-source Java tool that handles persistence for relational databases, XML, and
web services.

4. Jooq :
- jOOQ generates Java code based on your database and helps you build type-safe SQL queries.

5. Oracle TopLink :
- Oracle TopLink is used to create high-performance applications that can store data as either
relational records or XML elements.

Benefits of ORM :
- Simplifies Database Operations : Mapping allows developers to work with objects instead of
complex SQL queries. It simplifies database operations such as insertion, retrieval, updating, and
deletion.

- Provides Abstraction : Mapping hides the complexities of the database, allowing developers to
concentrate on the application's domain model and business logic without worrying about the details
of SQL.

- Improves Maintainability : With mapping, changes to the database schema can be easily managed by
updating the mapping settings, rather than modifying the entire application code.

- Enhances Performance : Hibernate's mapping features create efficient SQL queries and reduce the
number of database interactions, improving the overall performance.
INTRODUCTION TO HIBERNATE :
- Hibernate is an open-source ORM framework for Java that simplifies working with databases. It
automatically maps Java objects to database tables, making it easier to save, retrieve, and manipulate
data without needing to write complex SQL queries or handle database details manually. This helps
developers focus more on their application logic rather than database operations.
- Hibernate allows developers to use persistent objects that represent the data in their application. It
uses configuration files or annotations to define mapping between java objects and database tables.
This provides transparent persistence, meaning any changes made to the objects are automatically
updated in the database, keeping the data consistent without extra coding effort.

- Hibernate offers several key features, including :


1. Object-Relational Mapping : Hibernate maps Java classes to database tables and allows developers
to perform CRUD operations on objects instead of writing SQL.

2. Automatic SQL Generation : Hibernate automatically generates the SQL statements needed for
database interactions based on defined mappings, reducing manual SQL coding.

3. Transparent Persistence : Changes made to objects are automatically updated in the database,
helping maintain data consistency without extra code.

4. Caching : Hibernate uses first-level and second-level caching to improve performance by


minimizing direct database access.

5. Querying : Hibernate offers HQL (Hibernate Query Language), which is an object-oriented query
language similar to SQL, which works directly with objects and their properties.

6. Transaction Management : Hibernate simplifies database transaction management, providing built-


in support to handle transactions smoothly.

7. Database Independence : Hibernate abstracts the specific details of the underlying database,
enabling applications to work across different databases with minimal changes.

By using Hibernate, developers can focus more on the business logic and application development, as
Hibernate handles the complex database operations. It provides a powerful and flexible solution for
managing data persistence in Java applications, making it a popular choice for large-scale, enterprise-
level projects.
EXPLORING THE HIBERNATE ARCHITECTURE :
The Hibernate framework uses a layered architecture that consists of various components working
together to provide object-relational mapping and persistence capabilities.

The architecture of Hibernate can be divided into the following layers :


1. Application Layer :
- Application : The topmost layer in the Hibernate architecture. It represents your Java application,
which directly interacts with Hibernate to manage data persistence.

2. Hibernate Configuration Layer :


- Configuration : This layer is responsible for handling configuration settings required by Hibernate,
such as database connection details, mapping information, and other runtime configurations.
- SessionFactory : It is responsible for creating and managing sessions, which are used to interact with
the database. The SessionFactory is typically created during application startup and is shared
throughout the application

3. Persistent Classes and Object-Relational Mapping Layer :


- Persistent Classes : These are the main classes in the application that represent the data to be saved
in the database. They are typically annotated with Hibernate annotations or set up using XML define
how these classes connect to the database tables.
- Mapping Metadata : Hibernate uses metadata, which can be either in the form of annotations or
XML files, to define the relationship between the classes and database tables, as well as the mapping
of attributes to table columns.

4. Hibernate Core Layer :


- Session : The Session is a runtime interface between the application and Hibernate. It represents a
specific task and allows you to perform CRUD operations, run queries, and handle transactions.
- Transaction : This Transaction component manages database transactions, making sure that changes
made during a transaction are properly saved or rolled back in case of errors.
- Hibernate Query Language (HQL) : HQL is an object-oriented query language provided by
Hibernate that allows developers to write database queries using object-oriented concepts instead of
SQL.
- Criteria API : Hibernate provides a Criteria API that allows for construction of database queries
using a fluent and type-safe API.
5. JDBC Layer :
- JDBC : Hibernate uses JDBC to communicate with the database. JDBC handles database
interactions, such as executing SQL statements, managing database connections, and retrieving
results.

The layered architecture of Hibernate breaks down the tasks involved in database operations into
separate parts. This approach makes it easier to manage and develop Java applications with database
interactions by clearly separating database connectivity, persistence management, and application
logic.

You might also like