Java Unit III
Java Unit III
Unit – III
Topic: java Database Connectivity (JDBC)
Introduction:
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls.
Oracle does not support the JDBC-ODBC Bridge from Java Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.
Advantage:
Disadvantage:
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That
is why it is known as thin driver. It is fully written in Java language.
Advantage:
Disadvantage:
1. Application
2. The JDBC API
3. DriverManager
4. JDBC Drivers
5. Data Sources
Application
Applications in JDBC architecture are java applications like applets or servlet that communicates
with databases.
JDBC API
The JDBC API is an Application Programming Interface used to create Databases. JDBC API
uses classes and interfaces to connect with databases. Some of the important classes and
interfaces defined in JDBC architecture in java are the DriverManager class, Connection
Interface, etc.
DriverManager
JDBC Drivers
JDBC drivers are used to connecting with data sources. All databases like Oracle, MSSQL,
MYSQL, etc. have their drivers, to connect with these databases we need to load their specific
drivers. Class is a java class used to load drivers. Class.forName() method is used to load
drivers in JDBC architecture.
Data Sources
Data Sources in the JDBC architecture are the databases that we can connect using this API.
These are the sources where data is stored and used by Java applications. JDBC API helps to
connect various databases like Oracle, MYSQL, MSSQL, PostgreSQL, etc.
The JDBC Architecture can be of two types based on the processing models it uses. These
models are
1. 2-tier model
2. 3-tier model
2 Tier Model
2-tier JDBC architecture model is a basic model.
In this model, a java application communicates directly to the data sources. JDBC driver
is used to establish a connection between the application and the data source.
When an application needs to interact with a database, a query is directly executed on the
data source and the output of the queries is sent back to the user in form of results.
In this model, the data source can be located on a different machine connected to the
same network the user is connected to.
This model is also known as a client/server configuration. Here user's machine acts as a
client and the machine on which the database is located acts as a server.
3 Tier Model
3-tier model is a complex and more secure model of JDBC architecture in java.
In this model the user queries are sent to the middle tier and then they are executed on the
data source.
Here, the java application is considered as one tier connected to the data source(3rd tier) using
middle-tier services.
In this model user queries are sent to the data source using middle-tier services, from where the
commands are again sent to databases for execution.
The results obtained on the database are again sent to the middle-tier and then to the
user/application.
Working of JDBC
Java applications need to be programmed for interacting with data sources. JDBC Drivers for
specific databases are to be loaded in a java application for JDBC support which can be done
dynamically at run time. These JDBC drivers communicate with the respective data source.
3. Create Query: To manipulate the database we need to create a query using commands like
INSERT, UPDATE, DELETE, etc. These queries are created and stored in string format.
Syntax: String sql_query = "INSERT INTO Student(name, roll_no) values('ABC','XYZ')"
Syntax: Statement St = con.createStatement();
5. Execute Statement: To execute SQL statements on the database we can use two methods
depending on which type of query we are executing.
Execute Update: Execute update method is used to execute queries like insert, update, delete,
etc. Return type of executeUpdate() method is int.
Execute Query: Execute query method is used to execute queries used to display data from the
database, such as select. Return type of executeQuery() method is result set.
Syntax: Resultset = st.executeUpdate(sql);
Synatx: con.close();
Q) Explain Jdbc classes and Interfaces
Interfaces of JDBC API
JDBC API uses various interfaces to establish connections between applications and data
sources. Some of the popular interfaces in JDBC API are as follows:
Driver interface - The JDBC Driver interface provided implementations of the abstract classes
such as java.sql.Connection, Statement, PreparedStatement, Driver, etc. provided by the JDBC
API.
Connection interface - The connection interface is used to create a connection with the
database. getConnection() method of DriverManager class of the Connection interface is used
to get a Connection object.
Statement interface - The Statement interface provides methods to execute SQL queries on the
database. executeQuery(), executeUpdate() methods of the Statement interface are used to run
SQL queries on the database.
ResultSet interface - ResultSet interface is used to store and display the result obtained by
executing a SQL query on the database. executeQuery() method of statement interface returns
a resultset object.
RowSet interface - RowSet interface is a component of Java Bean. It is a wrapper of ResultSet
and is used to keep data in tabular form.
ResultSetMetaData interface - Metadata means data about data. ResultSetMetaData interface
is used to get information about the resultset interface. The object of the ResultSetMetaData
interface provides metadata of resultset like number of columns, column name, total records,
etc.
DatabaseMetaData interface - DatabaseMetaData interface is used to get information about
the database vendor being used. It provides metadata like database product name, database
product version, total tables/views in the database, the driver used to connect to the database,
etc.
Along with interfaces, JDBC API uses various classes that implement the above interfaces.
Methods of these classes in JDBC API are used to create connections and execute queries on
databases. A list of most commonly used class in JDBC API are as follows:
import java.sql.*;
import java.util.*;
class Main {
{
// Creating the connection using Oracle DB
System.out.println("enter name");
System.out.println("enter class");
// Inserting data using SQL query
// Try block to check for exceptions
try {
// Registering drivers
DriverManager.registerDriver(
new oracle.jdbc.OracleDriver());
// Reference to connection interface
pass);
// Creating a statement
Statement st = con.createStatement();
// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println(
else
System.out.println("insertion failed");
// Closing the connections
con.close();
}
// Catch block to handle exceptions
System.err.println(ex);
}
}
Output:
while(resultSet.next()) {
// ...
}
Note that the ResultSet object is positioned at the first row by executing the next() method when
entering the loop, because, as already mentioned, the ResultSet object is initially located at a
position just before the first row. So, it must be put to at least the first row, for example, to get a
valid record. It may be deemed as a value -1 in an array position a pointer/index is pointing to. It
must be first relocated to at least the 0th location to get any kind of valid value from the array.
Now, as we have mentioned, we can scroll through records with the help of the ResultSet object.
But, this ability does not come by default. The default behavior of the ResultSet object is that it is
not updatable and the cursor it owns actually moves in one direction, forward only. This means
that we can iterate through the records only once and in a forward direction only. However, there
are ways to make it flexible so that the ResultSet is not only updatable but also scrollable.
Scrollable ResultSet
Let’s first make the ResultSet object scrollable. Scrollable means that once
the ResultSet object has been created, we can traverse through fetched records in
any direction, forward and backward, as we like. This provides the ability to read
the last record, first record, next record, and the previous record.
package org.mano.example;
import java.sql.*;
public class App
"com.mysql.cj.jdbc.Driver";
"jdbc:mysql://localhost:3306/employees";
ResultSet rs = null;
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection
catch(Exception ex)
ex.printStackTrace();
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);){
System.out.println("n2.
rs = pstmt.executeQuery();
System.out.println("n3.
System.out.println("n4.
rs.first();
show(rs);
rs.last();
show(rs);
rs.previous();
rs.previous();
show(rs);
rs.next();
show(rs);
}catch(SQLException ex){
ex.printStackTrace();
}finally{
try {
connection.close();
}catch(SQLException ex){
SQLException{
System.out.printf
("n--------------------------------"+
"-------------------------------------");
| %s | %s ",rs.getLong("emp_no"),
rs.getString("first_name"),
rs.getString("last_name"),
rs.getDate("birth_date").toString(),
rs.getDate("hire_date"),
rs.getString("gender"));
System.out.printf
("n---------------------------------"+
"------------------------------------");
Output
1. Connection established.
2. Executing SQL query…
3. ResultSet object created successfully.
4. Now, some RecordSet scrolling starts…
5. -------------------------------------------------------------
7. -------------------------------------------------------------
8. -------------------------------------------------------------
10.-------------------------------------------------------------
11.-------------------------------------------------------------
13.-------------------------------------------------------------
14.-------------------------------------------------------------
16.-------------------------------------------------------------
Updatable ResultSet
Creating an updatable ResultSet means that the record it points to is not only be
traversable but also be updatable. The changes will immediately be persisted in the
database and reflected by the ResultSet object in real time.
package org.mano.example;
import java.sql.*;
"com.mysql.cj.jdbc.Driver";
"jdbc:mysql://localhost:3306/employees";
ResultSet rs = null;
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection
System.out.println("n1.
Connection established");
}catch(Exception ex) {
ex.printStackTrace();
try(PreparedStatement pstmt =
connection.prepareStatement(SQL,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);){
pstmt.setLong(1,emp_no);
System.out.println("n2.
rs = pstmt.executeQuery();
System.out.println("n3.
while(rs.next()){
show(rs);
System.out.println("n4.
rs.updateString("first_name", "Subham");
rs.updateRow();
System.out.println("nn5.
rs.previous();
show(rs);
}catch(SQLException ex){
ex.printStackTrace();
}finally{
try {
rs.close();
connection.close();
}catch(SQLException ex){
}
throwsSQLException{
System.out.printf
("n--------------------------------"+
"-------------------------------------");
| %s | %s ",rs.getLong("emp_no"),
rs.getString("first_name"),
rs.getString("last_name"),
rs.getDate("birth_date").toString(),
rs.getDate("hire_date"),
rs.getString("gender"));
System.out.printf
("n---------------------------------"+
"------------------------------------");
Hibernate:
Hibernate Framework
Hibernate is a Java framework that simplifies the development of Java application to interact
with the database. It is an open source, lightweight, ORM (Object Relational Mapping) tool.
Hibernate implements the specifications of JPA (Java Persistence API) for data persistence.
ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.
The ORM tool internally uses the JDBC API to interact with the database.
POJO
POJO in Java stands for Plain Old Java Object. It is an ordinary object, which is not bound by
any special restriction. The POJO file does not require any special classpath. It increases the
readability & re-usability of a Java program.
POJOs are now widely accepted due to their easy maintenance. They are easy to read and write.
A POJO class does not have any naming convention for properties and methods. It is not tied to
any Java Framework; any Java Program can use it.
The POJO classes are similar to Beans as both are used to define the objects to increase the
readability and re-usability. The only difference between them that Bean Files have some
restrictions but, the POJO files do not have any special restrictions.
Example:
POJO class is used to define the object entities. For example, we can create an Employee POJO
class to define its objects.
Employee.java:
// POJO class Exmaple
package Jtp.PojoDemo;
public class Employee {
private String name;
private String id;
private double sal;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
}
Output:
Name: Alisha
Id: A001
Salary: 200000.0
From the above example, we can see we have accessed the POJO class properties in
MainClass.java.
o A no-arg constructor: It is recommended that you have a default constructor at least package
visibility so that hibernate can create the instance of the Persistent class by newInstance() method.
o Provide an identifier property: It is better to assign an attribute as id. This attribute behaves as
a primary key in database.
o Declare getter and setter methods: The Hibernate recognizes the method by getter and setter
method names by default.
o Prefer non-final class: Hibernate uses the concept of proxies, that depends on the persistent
class. The application programmer will not be able to use proxies for lazy association fetching.
Employee.java
package com.javatpoint.mypackage;
public class Employee {
private int id;
private String firstName,lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
The mapping file name conventionally, should be class_name.hbm.xml. There are many elements of the
mapping file.
o hibernate-mapping : It is the root element in the mapping file that contains all the mapping
elements.
o class : It is the sub-element of the hibernate-mapping element. It specifies the Persistent class.
o id : It is the subelement of class. It specifies the primary key attribute in the class.
o generator : It is the sub-element of id. It is used to generate the primary key. There are many
generator classes such as assigned, increment, hilo, sequence, native etc. We will learn all the
generator classes later.
o property : It is the sub-element of class that specifies the property name of the Persistent class.
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
The configuration file contains information about the database and mapping file. Conventionally, its name
should be hibernate.cfg.xml .
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class StoreData {
public static void main(String[] args) {
//Create typesafe ServiceRegistry object
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build
();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Employee e1=new Employee();
e1.setId(101);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
For successfully running the hibernate application, you should have the hibernate5.jar file.
We may run this hibernate application by IDE (e.g. Eclipse, Myeclipse, Netbeans etc.) or without IDE.
We will learn about creating hibernate application in Eclipse IDE in next chapter.
o Transient state
o Persistent state
o Detached state
Transient state
1. Employee e=new Employee(); //Here, object enters in the transient state.
2. e.setId(101);
3. e.setFirstName("Gaurav");
4. e.setLastName("Chawla");
Persistent state
o As soon as the object associated with the Session, it entered in the persistent state.
o Hence, we can say that an object is in the persistence state when we save or persist it.
o Here, each object represents the row of the database table.
o So, modifications in the data make changes in the database.
We can use any of the following methods for the persistent state.
1. session.save(e);
2. session.persist(e);
3. session.update(e);
4. session.saveOrUpdate(e);
5. session.lock(e);
6. session.merge(e);
Detached State
o Once we either close the session or clear its cache, then the object entered into the
detached state.
o As an object is no more associated with the Session, modifications in the data don't affect
any changes in the database.
o However, the detached object still has a representation in the database.
o If we want to persist the changes made to a detached object, it is required to reattach the
application to a valid Hibernate session.
o To associate the detached object with the new hibernate session, use any of these
methods - load(), merge(), refresh(), update() or save() on a new session with the
reference of the detached object.
We can use any of the following methods for the detached state.
o session.close();
o session.clear();
o session.detach(e);
o session.evict(e);
o by annotation
o by mapping file.
o Hibernate Named Query by annotation
o If you want to use named query in hibernate, you need to have knowledge of @NamedQueries
and @NamedQuery annotations.
o @NameQueries annotation is used to define the multiple named queries.
o @NameQuery annotation is used to define the single named query.