Java - 2 Meet Ref
Java - 2 Meet Ref
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 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 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.
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.
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.
- 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.
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:
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.
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.
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.
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.
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.
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 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.