0% found this document useful (0 votes)
24 views38 pages

15 To 19 Hibernate

Hibernate is an object-relational mapping tool that simplifies the development of Java applications to interact with databases. It maps Java objects to database tables and allows developers to interact with data using Java objects rather than direct SQL queries. Hibernate aims to overcome some of the drawbacks of traditional JDBC usage such as handling database connections and exceptions, and allows objects to be passed between layers rather than converting them to text.

Uploaded by

Hari Chandrudu M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views38 pages

15 To 19 Hibernate

Hibernate is an object-relational mapping tool that simplifies the development of Java applications to interact with databases. It maps Java objects to database tables and allows developers to interact with data using Java objects rather than direct SQL queries. Hibernate aims to overcome some of the drawbacks of traditional JDBC usage such as handling database connections and exceptions, and allows objects to be passed between layers rather than converting them to text.

Uploaded by

Hari Chandrudu M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Hibernate

ORM Tool

CREATED BY K. VICTOR BABU


Hibernate is a framework that simplifies the development of Java application to interact with the
database.

CREATED BY K. VICTOR BABU


Draw Backs of JDBC:

1. In JDBC, if we open a database connection we need to write in try, and if any exceptions occurred catch

block will takers about it, and finally used to close the connections.

2. In JDBC we need to write SQL commands in various places, after the program has created if the table

structure is modified then the JDBC program doesn’t work, again we need to modify and compile and re-

deploy required, which is tedious.

3. JDBC used to generate database related error codes if an exception will occurs, but java programmers are

unknown about this error codes right.

4. In the Enterprise applications, the data flow with in an application from class to class will be in the form of

objects, but while storing data finally in a database using JDBC then that object will be converted into text.

 Because JDBC doesn’t transfer objects directly.

CREATED BY K. VICTOR BABU


Introduction

• Hibernate is the ORM (Object-relational mapping) tool given to transfer the data between a
java (object) application and a database (Relational) in the form of the objects.  Hibernate is
the open source light weight tool given by Gavin King in 2001.

• Hibernate is a non-invasive framework,  means it wont forces the programmers to


extend/implement any class/interface, and in hibernate we have all POJO (Plain Old Java
Object) classes so its light weight.

• Hibernate can runs with in or with out server, I mean it will suitable for all types of java
applications

• Hibernate is purely for persistence (to store/retrieve data from Database).

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
• In Jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws,
but in hibernate we only have Un-checked exceptions, so no need to write try, catch, or no need
to write throws.  Actually in hibernate we have the translator which converts checked to Un-
checked

• Hibernate has capability to generate primary keys automatically while we are storing the
records into database

• Hibernate has its own query language, i.e hibernate query language which is database
independent

• So if we change the database, then also our application will works as HQL is database
independent

• HQL contains database independent commands

CREATED BY K. VICTOR BABU


• While we are inserting any record using JDBC, if we don’t have any particular table in the
database, JDBC will rises an error like “View not exist”, and throws exception, but in case of
hibernate, if it not found any table in the database this will create the table for us .

• Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead
we use the methods provided by that API.

• Getting pagination in hibernate is quite simple.

CREATED BY K. VICTOR BABU


Disadvantages of Hibernate

• I don’t think there are disadvantages in hibernate

• You know some thing.., Its saying hibernate is little slower than pure JDBC, actually the reason
being hibernate used to generate many SQL statements in run time, but I guess this is not the
disadvantage

• But there is one major disadvantage, which was boilerplate code issue, actually we need to
write same code in several files in the same application, but spring eliminated this

CREATED BY K. VICTOR BABU


Minimum Number of files required in Hibernates:

• POJO class (JAVA file)


• Mapping file (XML file)
• Configuration file (XML file)
• One java file to write our logic (JAVA file)

are very familiar keywords we used to here in the hibernate, every hibernate program must
need these 2 xml files.

CREATED BY K. VICTOR BABU


POJO CLASS

• POJO is a simple java file, no need to extend any class or implement any interface.

• This POJO class contain private properties variables, and for each property a setter and a
getter.

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
CREATED BY K. VICTOR BABU
CREATED BY K. VICTOR BABU
Mapping:

• Mapping file is the heart of hibernate application.

• Every ORM tool needs this mapping, mapping is the mechanism of placing an object
properties into column’s of a table.

• Mapping can be given to an ORM tool either in the form of an XML or in the form of the
annotations.

• The mapping file contains mapping from a pojo class name to a table name and pojo class
variable names to table column names.

• While writing an hibernate application, we can construct one or more mapping files, mean a
hibernate application can contain any number of  mapping files.

CREATED BY K. VICTOR BABU


• object contains 3 properties like
• Identity (Object Name)

• State (Object values)

• Behavior (Object Methods)

• while storing an object into the database, we need to store only the values(State) right ? but
how to avoid identity, behavior.. its not possible. In order to inform what value of an object
has to be stored in what column of the table, will be taking care by the mapping.

CREATED BY K. VICTOR BABU


Syntax Of Mapping xml:

<hibernate-mapping>

<class name="POJO class name" table="table name in database">

<id name="variable name" column="column name in database" type="java/hibernate type" />

<property name="variable1 name" column="column name in database" type="java/hibernate type" />

<property name="variable2 name" column="column name in database" type="java/hibernate type" />

</class>

</hibernate-mapping>

Number of POJO classes = that many number of mapping xml files


Note: id is used for key attribute remaining all are property

CREATED BY K. VICTOR BABU


Configuration:

• Configuration is the file loaded into an hibernate application when working with hibernate,
this configuration file contains 3 types of information..
• Connection Properties

• Hibernate Properties

• Mapping file name(s)

• We must create one configuration file for each database we are going to use, suppose if we
want to connect with 2 databases, like Oracle, MySql, then we must create 2 configuration
files.

No. of databases we are using  = That many number of configuration files

CREATED BY K. VICTOR BABU


<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>

<!-- Related to the connection START -->

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver </property>

<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>

<property name="connection.user">user</property>

<property name="connection.password">password</property>
<!-- Related to the connection END -->

CREATED BY K. VICTOR BABU


<!-- Related to hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialet">org.hibernate.dialect.OracleDialect</property>
<property name="hbm2ddl.auto">update</property>
<!-- Related to hibernate properties END -->

<!-- Related to mapping START -->


<mapping resource="Our mapping xml file name" />
<!-- Related to the mapping END -->

</session-factory>
</hibernate-configuration>

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
• Mapping –> xml, annotations

• Configuration –> xml, .properties (old style)

CREATED BY K. VICTOR BABU


Example (POJO Class) (HibernateSample.java)
public class HibernateSample public void setStName(int stName)
{ {
this.stName=stName;
private int stNo; }
private String stName; public String getStName()
private String stAddress; {
return stName;
}
public void setStno(int stNo) public void setStAddress(String stAddress)
{ {
this.stAddress=stAddress;
this.stNo=stNo; }
} public String getStAddress()
{
public int getStNo()
return stAddress;
{ }}
return stNo;
}

CREATED BY K. VICTOR BABU


Mapping XML file related to POJO (Sample.hbm.xml)

<hibernate-mapping>
<class name=" HibernateSample" table="STable">
<id name="stNo" column="SNo">
<generator class="assigned"/> </id>
<property name="stName" column="SName" />
<property name="stAddress "/> </class>
</hibernate-mapping>

CREATED BY K. VICTOR BABU


Configuration file (hibernate.cfg.xml)

<?xml version='1.0' encoding='UTF-8'?>


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-
3.0.dtd">
<hibernate-configuration>
<session-factory>

CREATED BY K. VICTOR BABU


<!-- Related to the connection START -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE </property>
<property name="connection.user">system</property>
<property name="connection.password">rajesh</property>
<!-- Related to the connection END -->

CREATED BY K. VICTOR BABU


<!-- Related to hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialet">org.hibernate.dialect.OracleDialect</property>
<property name="hbm2ddl.auto">update</property>
<!-- Related to hibernate properties END -->

<!-- Related to mapping START -->


<mapping resource="Our mapping xml file name" />
<!-- Related to the mapping END -->

</session-factory>
</hibernate-configuration>

CREATED BY K. VICTOR BABU


Execution flow and Example

Hibernate Framework Flow, How To Work With Hibernate.txt

Hibernate Hello World Example.txt

CRUD.docx

Inheritance Mapping in Hibernate.docx

CREATED BY K. VICTOR BABU


HQL

Example of HQL to get all the records

Query query=session.createQuery("from Emp");


List list=query.list();

CREATED BY K. VICTOR BABU


Example of HQL to get records with pagination

Query query=session.createQuery("from Emp");


query.setFirstResult(5);
query.setMaxResult(10);
List list=query.list();

CREATED BY K. VICTOR BABU


Example of HQL update query

Transaction tx=session.beginTransaction();
Query q=session.createQuery("update User set name=:n where id=:i");
q.setParameter("n","Udit Kumar");
q.setParameter("i",111);

int status=q.executeUpdate();
System.out.println(status);
tx.commit();

CREATED BY K. VICTOR BABU


Example of HQL delete query

Query query=session.createQuery("delete from Emp where id=100");


query.executeUpdate();

CREATED BY K. VICTOR BABU


HQL with Aggregate functions

• Example to get total salary of all the employees


Query q=session.createQuery("select sum(salary) from Emp");
List<Integer> list=q.list();
System.out.println(list.get(0));

CREATED BY K. VICTOR BABU


Example to get maximum salary of employee
Query q=session.createQuery("select max(salary) from Emp"); 

Example to get minimum salary of employee


Query q=session.createQuery("select min(salary) from Emp"); 

Example to count total number of employee ID


Query q=session.createQuery("select count(id) from Emp");

Example to get average salary of each employees


Query q=session.createQuery("select avg(salary) from Emp");

CREATED BY K. VICTOR BABU


HCQL (Hibernate Criteria Query Language)
The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the specific criteria. The Criteria interface

provides methods to apply criteria such as retreiving all the records of table whose salary is greater than 50000 etc.

Advantage of HCQL

• The HCQL provides methods to add criteria, so it is easy for the java programmer to add criteria. The java programmer is

able to add many criteria on a query.

• Criteria Interface

• The Criteria interface provides many methods to specify criteria. The object of Criteria can be obtained by calling the

createCriteria() method of Session interface.

Syntax of createCriteria() method of Session interface

public Criteria createCriteria(Class c)  

CREATED BY K. VICTOR BABU


Restrictions class

Restrictions class provides methods that can be used to provide criteria on query.
1. lt()
2. gt()
3. le()
4. ge()
5. eq()
6. ne()

CREATED BY K. VICTOR BABU


• Order Class
1. asc()
2. desc(

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
CREATED BY K. VICTOR BABU

You might also like