Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
117 views

Java Unit III

The document discusses Java Database Connectivity (JDBC) which is a Java API used to connect Java applications to databases. It describes the four types of JDBC drivers: JDBC-ODBC bridge driver, native driver, network protocol driver, and thin driver. It also provides details about the architecture of JDBC including its major components like the JDBC API, DriverManager, JDBC drivers, data sources, and the 2-tier and 3-tier models. Finally, it explains the key JDBC interfaces like Driver, Connection, Statement, ResultSet, and DatabaseMetaData.

Uploaded by

LALITH MOHAN
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views

Java Unit III

The document discusses Java Database Connectivity (JDBC) which is a Java API used to connect Java applications to databases. It describes the four types of JDBC drivers: JDBC-ODBC bridge driver, native driver, network protocol driver, and thin driver. It also provides details about the architecture of JDBC including its major components like the JDBC API, DriverManager, JDBC drivers, data sources, and the 2-tier and 3-tier models. Finally, it explains the key JDBC interfaces like Driver, Connection, Statement, ResultSet, and DatabaseMetaData.

Uploaded by

LALITH MOHAN
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Advanced java programming

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:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver

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.

Q) Explain JDBC Drivers Briefly ?:


JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver

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:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.


o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

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:

o Network support is required on client machine.


o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

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:

o Better performance than all other drivers.


o No software is required at client side or server side.

Disadvantage:

o Drivers depend on the Database.

Q) Explain Briefly Architecture of JDBC ?


As we can see in the above image the major components of JDBC
architecture are as follows:

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

DriverManager class in the JDBC architecture is used to establish a connection between Java


applications and databases. Using the getConnection method of this class a connection is
established between the Java application and data sources.

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.

Types of JDBC Architecture

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.

Steps to connect a Java program using JDBC API. 

1. Load Driver: Load JDBC Driver for specific databases using forName() method of


class Class. Syntax: Class.forName("com.mysql.jdbc.Driver")

2. Create Connection: Create a connection with a database using DriverManager class.


Database credentials are to be passed while establishing the connection.
Syntax: DriverManager.getConnection()

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')"

4. Create Statement: The query we have created is in form of a string. To perform the


operations in the string on a database we need to fire that query on the database. To achieve this
we need to convert a string object into SQL statements. This can be done
using createStatement() and prepareStatement() interfaces.

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.

Syntax: int check = st.executeUpdate(sql);

 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);

6. Closing Statement: After performing operations on the database, it is better to close


every interface object to avoid further conflicts.

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.

Classes of JDBC API

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:

 DriverManager class - DriverManager class is a member of the java.sql package. It is used to


establish a connection between the database and its driver.
 Blob class - A java.sql.Blob is a binary large object that can store large amounts of binary data,
such as images or other types of files. Fields defined as TEXT also hold large amounts of data.
 Clob class - The java.sql.Clob interface of the JDBC API represents the CLOB datatype. Since the
Clob object in JDBC is implemented using an SQL locator, it holds a logical pointer to the SQL
CLOB (not the data).
 Types class - Type class defined and store constants that are used to identify generic SQL types
also known as JDBC types.

Java Program to Establish Connection in JDBC


 // Importing database

import java.sql.*;

// Importing required classes

import java.util.*;

 // Main class

class Main {

   // Main driver method

    public static void main(String a[])

    {

 
        // Creating the connection using Oracle DB

        // Note: url syntax is standard, so do grasp

        String url = "jdbc:oracle:thin:@localhost:1521:xe";

  // Username and password to access DB

        // Custom initialization

        String user = "system";

        String pass = "12345";

   // Entering the data

        Scanner k = new Scanner(System.in);

  System.out.println("enter name");

        String name = k.next();

 System.out.println("enter roll no");

        int roll = k.nextInt();

  System.out.println("enter class");

        String cls = k.next();

 
        // Inserting data using SQL query

        String sql = "insert into student1 values('" + name

                     + "'," + roll + ",'" + cls + "')";


 
        // Connection class object

        Connection con = null;

 
        // Try block to check for exceptions

        try {

 
            // Registering drivers

            DriverManager.registerDriver(

                new oracle.jdbc.OracleDriver());

 
            // Reference to connection interface

            con = DriverManager.getConnection(url, user,

                                              pass);

 
            // Creating a statement

            Statement st = con.createStatement();

 
            // Executing query

            int m = st.executeUpdate(sql);

            if (m == 1)

                System.out.println(

                    "inserted successfully : " + sql);

            else

                System.out.println("insertion failed");

 
            // Closing the connections

            con.close();

        }
 
        // Catch block to handle exceptions

        catch (Exception ex) {

            // Display message when exceptions occurs

            System.err.println(ex);

        }

    }

Output:

Executing the Statements


After creating the statement objects, you need to execute them. To execute the statements, the
Statement interface provides three methods namely, execute(), executeUpdate() and,
executeQuery().
 execute(): Used to execute SQL DDL statements, it returns a boolean value specifying
whether the ResultSet object can be retrieved.
 executeUpdate(): Used to execute statements such as insert, update, delete. It returns an
integer value representing the number of rows affected.
 executeQuery(): Used to execute statements that returns tabular data (example select). It
returns an object of the class ResultSet.
Execute the created statement using one of these methods.
stmt.execute(query);
stmt.executeQuery(query);
stmt.execute(query);

Processing the Result


Once you execute the statements/queries you will get the result of the respective query as a
return value from execute() (boolean value) or, executeQuery() (ResultSet)
or, executeUpdate() (integer value) methods.
The ResultSet object holds tabular values and it has a pointer that points to the rows of the table,
initially the pointer/cursor will be positioned before the first row. Once you get a ResultSet
object you need to retrieve required values from it and process.
You can move the pointer to the next row using the next() method. This returns a boolean value
specifying whether the ResultSet contains next row.
Therefore, using this method in the while loop you can iterate the contents of the result set and
get the contents of the columns of that row using the getter methods of the Statement interface.
while(rs.next()) {
System.out.print("Brand: "+rs.getString("Mobile_Brand")+", ");
System.out.print("Sale: "+rs.getString("Unit_Sale"));
System.out.println("");
}

Q) Expalin Scrollable and updatable Resultset


The ResultSet is an interface defined in the java.sql package. It represents a table of data returned
by a Statement object. A Statement object is used to execute SQL queries to the database. The
ResultSet object maintains a cursor pointing to the current record in the database table. As a
result, it can be effectively used to position at different rows, back and forth
using first(), previous(), next(), and last() methods as per requirements. Initially,
the ResultSet object is positioned at a location before the first row. This is the reason
a ResultSet traversal always begins as follows:

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

static final String JDBC_DRIVER =

"com.mysql.cj.jdbc.Driver";

static final String DB_URL =

"jdbc:mysql://localhost:3306/employees";

static final String USER = "root";

static final String PASS = "secret";

static final String SQL =

"SELECT * FROM employees ORDER BY first_name";

public static void main( String[] args )

Connection connection = null;

ResultSet rs = null;

try {

Class.forName(JDBC_DRIVER);

connection = DriverManager.getConnection

(DB_URL, USER, PASS);

System.out.println("n1. Connection established");

catch(Exception ex)

ex.printStackTrace();

try (PreparedStatement pstmt =


connection.prepareStatement(SQL,

ResultSet.TYPE_SCROLL_INSENSITIVE,

ResultSet.CONCUR_READ_ONLY);){

System.out.println("n2.

Executing SQL query...");

rs = pstmt.executeQuery();

System.out.println("n3.

ResultSet object created successfully.");

System.out.println("n4.

Now some RecordSet scrolling starts...");

rs.first();

show(rs);

rs.last();

show(rs);

rs.previous();

rs.previous();

show(rs);

rs.next();

show(rs);

System.out.println("nn5. That's all.

RecordSet scrolling ends.");

}catch(SQLException ex){

ex.printStackTrace();

}finally{

try {
connection.close();

}catch(SQLException ex){

public static void show(ResultSet rs) throws

SQLException{

System.out.printf

("n--------------------------------"+

"-------------------------------------");

System.out.printf("n%7d | %10s | %10s | %s

| %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. -------------------------------------------------------------

6. 497615 | Aamer | McDermid | 1954-11-18 | 1985-04-24 | M

7. -------------------------------------------------------------

8. -------------------------------------------------------------

9. 484995 | Zvonko | Lakshmanan | 1964-11-04 | 1992-12-04 | M

10.-------------------------------------------------------------

11.-------------------------------------------------------------

12. 482000 | Zvonko | Cannata | 1960-11-23 | 1986-08-13 | M

13.-------------------------------------------------------------

14.-------------------------------------------------------------

15. 483497 | Zvonko | Pollacia | 1961-12-26 | 1985-08-01 | M

16.-------------------------------------------------------------

That’s all. RecordSet scrolling ends.


Note that the scrollable ResultSet object is the result of the execution of
the executeQuery() method obtained through the instance
of Statement or PreparedStatement. The type of ResultSet object we like to create
must be explicitly declared to the Statement object through defined scroll type
constants.

 ResultSet.TYPE_FORWARD_ONLY: This is the default type.


 ResultSet.TYPE_SCROLL_INSENSITIVE: Enables back and forth
movement, but is insensitive to ResultSet updates.
 ResultSet.TYPE_SCROLL_SENSITIVE: Enables back and forth movement,
but is sensitive to ResultSet updates.
There are other constants used, such as CONCUR_READ_ONLY, which means
that the ResultSet is not updatable. There is another
constant, CONCUR_UPDATABLE, which signifies the opposite, meaning
the ResultSet is updatable.

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.*;

public class App

static final String JDBC_DRIVER =

"com.mysql.cj.jdbc.Driver";

static final String DB_URL =

"jdbc:mysql://localhost:3306/employees";

static final String USER = "root";

static final String PASS = "secret";

static final String SQL =

"SELECT * FROM employees WHERE emp_no = ?";

public static void main( String[] args )

Connection connection = null;

ResultSet rs = null;

long emp_no = 484995;

try {

Class.forName(JDBC_DRIVER);

connection = DriverManager.getConnection

(DB_URL, USER, PASS);

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.

Executing SQL query...");

rs = pstmt.executeQuery();

System.out.println("n3.

ResultSet object created successfully.");

while(rs.next()){

show(rs);

String fname = rs.getString("first_name");

System.out.println("n4.

Updating name "+fname+" to Subham");

rs.updateString("first_name", "Subham");

rs.updateRow();

System.out.println("nn5.

Record updated. See below.");

rs.previous();

show(rs);

}catch(SQLException ex){

ex.printStackTrace();

}finally{

try {

rs.close();

connection.close();

}catch(SQLException ex){
}

public static void show(ResultSet rs)

throwsSQLException{

System.out.printf

("n--------------------------------"+

"-------------------------------------");

System.out.printf("n%7d | %10s | %10s | %s

| %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.

Below is an example of Java POJO class:

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;  
}  
}  

Q) Creating a table using pojo class


/Using POJO class objects in MainClass Java program  
package Jtp.PojoDemo;  
public class MainClass 
{  
    public static void main(String[] args)
 {  
        // Create an Employee class object  
Employee obj= new Employee();  
obj.setName(“Alisha”); // Setting the values using the set() method  
obj.setId(“A001”);  
obj.setSal(200000);  
System.out.println(“Name: “+ obj.getName()); //Getting the values using the get() method  
System.out.println(“Id: “ + obj.getId());  
System.out.println(“Salary: “ +obj.getSal());  
    }  
}  

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.

Q) how to write a Hibernate application ?


1. Create the Persistent class
2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the first hibernate application by using command prompt

1) Create the Persistent class

A simple Persistent class should follow some rules:

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.

Let's create the simple Persistent class:

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;  
}  
  
  
}  

2) Create the mapping file for Persistent class

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.

Let's see the mapping file for the Employee 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>  

3) Create the Configuration file

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>  

4) Create the class that retrieves or stores the object


In this class, we are simply storing the employee object to the database.

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();    
        
}    
}   

5) Load the jar file

For successfully running the hibernate application, you should have the hibernate5.jar file.

Download the required jar files for hibernate

6) How to run the first hibernate application without IDE

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.

To run the hibernate application without IDE:

o Install the oracle10g for this example.


o Load the jar files for hibernate. (One of the way to load the jar file is copy all the jar files under
the JRE/lib/ext folder). It is better to put these jar files inside the public and private JRE both.
o Now, run the StoreData class by java com.javatpoint.mypackage.StoreData

Q) Object Life Cycle HQL (Hibernate)


Hibernate Lifecycle
In Hibernate, either we create an object of an entity and save it into the database, or we fetch the
data of an entity from the database. Here, each entity is associated with the lifecycle. The entity
object passes through the different stages of the lifecycle.

The Hibernate lifecycle contains the following states: -

o Transient state
o Persistent state
o Detached state
Transient state

o The transient state is the initial state of an object.


o Once we create an instance of POJO class, then the object entered in the transient state.
o Here, an object is not associated with the Session. So, the transient state is not related to
any database.
o Hence, modifications in the data don't affect any changes in the database.
o The transient objects exist in the heap memory. They are independent of Hibernate.

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);  

Q) Explain Hibernate Named Query?


The hibernate named query is way to use any query by some meaningful name. It is like using alias
names. The Hibernate framework provides the concept of named queries so that application programmer
need not to scatter queries to all the java code.

There are two ways to define the named query in hibernate:

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.

Let's see the example of using the named queries:


@NamedQueries(  
    {  
        @NamedQuery(  
        name = "findEmployeeByName",  
        query = "from Employee e where e.name = :name"  
        )  
    }  
)  

You might also like