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

Module - 10 - Hibernate

Here are the key points about caching in Hibernate: - Caching stores query results and entity states in memory to avoid hitting the database repeatedly for the same data. - This improves performance by reducing database access. Retrieving data from cache is much faster than querying the database. - There are 3 levels of caching in Hibernate - 1) First level cache (session-level cache) 2) Second level cache (entity-level cache) 3) Query cache - First level cache is enabled by default and caches data for a specific session. - Second level cache caches entities across sessions/transactions. It improves performance for frequently accessed entities. - Query cache caches query results to avoid executing

Uploaded by

Ganesh Kollati
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Module - 10 - Hibernate

Here are the key points about caching in Hibernate: - Caching stores query results and entity states in memory to avoid hitting the database repeatedly for the same data. - This improves performance by reducing database access. Retrieving data from cache is much faster than querying the database. - There are 3 levels of caching in Hibernate - 1) First level cache (session-level cache) 2) Second level cache (entity-level cache) 3) Query cache - First level cache is enabled by default and caches data for a specific session. - Second level cache caches entities across sessions/transactions. It improves performance for frequently accessed entities. - Query cache caches query results to avoid executing

Uploaded by

Ganesh Kollati
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 28

Module – 10

Hibernate
Introduction to Hibernate

 Hibernate is an ORM Tool (Object Relationship


Mapping).
 Hibernate is a framework.
 Hibernate is free. Developer need not buy this
software.
 Hibernate generates the SQL automatically.
User need not write the SQL.
 Hibernate reduces the development time.
Why not JDBC.

 It is very difficult to manage with JDBC for large


projects.
 JDBC does not support Object Oriented
concepts like encapsulation and Inheritance.
 It is difficult to implement MVC architecture with
JDBC.
 Queries are based on database not based on
the current project.
Hibernate - ORM.

 Business objects can directly access data objects rather than


tables. Helpful in DAO and DTO patterns.
 SQL query is generated by ORM, hence SQL Query is hidden.
 Hibernate is developed on top of JDBC.
 Need not write DB specific queries.
 Transaction Management like Commit() and Rollback() are
automatically taken care.
 Time consumption is less when compared to JDBC.
Hibernate

 Pls have a picture here..


 This picture has 2 rectangles and 1 db icon.
 . 1 rectange has Java application as text.
 2nd rectange contains Hibernate as text
 3rd is Databse icon.
 Bi-directional arrays from 1st rectange to 2nd and to the DB
ICON.
 I want to convey that data flows between java application to
hibernate and from hibernate to Databse and vice versa.
Hibernate Architecture.

 Pls make similar picture of this..


Hibernate Architecture.

 Pls make similar picture.


Hibernate Architecture...

 SessionFactory creates session.


 Session is an interface which connects between the application and data
stored in the databse. Session provides methods to Insert, update and
delete data in database.
 Transaction allows the application to define the units of work.
 ConnectiionProvider is a strategy for obtaining JDBC connections. The
ConnectionProvider interface is not intended to be exposed to the
application. Instead it is used internally by Hibernate to obtain connections.
Files required in Hibernate

 Hibernate configuration file → hibernate.cfg.xml → This file will


have database connection parameter.
 Java object which needs to be written in the db. This is a bean
class. This is a
 Hibernate mapping file → .hbm file. → This file will map the
bean class with database.
 Client class → This class is to test the hibernate application.
Hibernate.cfg.xml

<hibernate-configuration>

<session-factory>

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

<property name="hibernate.connection.url">jdbc:oracle:thin:@charan-
HP:1521:XE</property>

<property name="hibernate.connection.username">userid</property>

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

<property
name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>

<property name="show_sql">false</property>

<mapping resource="employee.hbm.xml"/>

</session-factory>

</hibernate-configuration>a
Hibernate.cfg.xml

 This is hibernae configuration file.


 This file will have Database configuration parameters like (a)
Driver class (b) Connection URL (c) User name, Pass word.
 Dialect is the one while converts the hibernate statements into
its corresponding SQL queries of the database.
 show_sql --> will display the generated sql in output console
window.
 Mapping resource --> will speicify the mapping file which maps
between class and db table.
Persistent class.

 A class which has the fields to be mapped with the database.


 This class has constructor with arguments.
 Getter and Setter methods for all the attributes of the class.
 Please write two rectanges here..
Employee.java employee table in db.
Id id
Firstname first_name
Lastname last_name
Salaray salary
Hbm file..

 Hbm file stands for Hibernate mapping.


 This file maps between persistent class and table. All the
fields are mapped one to one.
<hibernate-mapping>

<class name="Employee" table="EMPLOYEE">

<id name="id" type="int" column="id"> </id>

<property name="firstName" column="first_name" type="string"/>

<property name="salary" column="salary" type="int"/>

</class>

</hibernate-mapping>

This file maps Employee class with EMPLOYEE table. Class


attributes Id, firstname and salary are mapped with its
columns of the EMPLOYEE table respectively.
Client program.

 Connecting with the db.


Configuration conf = new Configuration().configure();

StandardServiceRegistryBuilder builder= new


StandardServiceRegistryBuilder().applySettings(conf.getProperties());

factory= conf.buildSessionFactory(builder.build());
 configuration object configure() uses the mappings and properties specified in the
hibernate.cfg.xml.
 ServiceRegistry is used to load the list of services in the hibernate.cfg.xml. Apart
from settings, some services to be exeucted also can be provided in the configuration
file.
 Using these services build the sessionFactory so that openSession of Session will
connect to the database for transactions.
For Add/list/update/delete

Following session methods are used to perform


add/update/delete/list records of the database.
Save (object) --> Saves the object in the database.
createQuery("FROM Employee").list() --> gets the
result of Select * from Employee and returns it in a
collection List.
Update() --> is used to udpate a record in the
database.
Delete() --> is used to delete a record from the
table.
Criteria and Restrictions.

 Criteria is an interface to query on a particular persistent class.


 Session has CreateCriteria() method which returns a Criteria object of a
particular class to fire the query on.
 Where clause of SQL can be added by using conditional methods of
Restrictions class. This can be added by add() method of Criteria class.
For example:
 Criteria c = new Criteria (Employee.class);
 c.add (Restritctions.gt (“salary”, 5000));
 List lst = cr.list();
 The above 3 lines create a criteria object c. With add() method of Criteria
object a condition is added as salary is > 5000. list() method of Criteria
object returns the result set in collection list.
 Trainer needs to demonstrate this program to the student
..Mapping in hibernate.

There are 3 types of relationship mappings in


database/hibernate. They are.
(a) One to One --> Example : One student has
one Teacher.
(b) One to Many --> Example : One Organization
has many employees.
(c) Many to Many --> Example : Many employees
has many certificates.
Relationship mapping pictures..

Pls add these image here...


http://docs.oracle.com/cd/E14571_01/web.1111/b32441/img/onetoo
ne_map_fig.gif

Many to one...
http://2.bp.blogspot.com/-QyLSI1zqdLA/T56sonkqKRI/AAAAAAAA
A5Y/W7A3jq0-I78/s1600/many-to-one.jpg

Many to Many --> Pls place icons for Employees and Projects
rather than ellipses.
http://www.expertsmind.com/CMSImages/411_Mapping
%20cardinality-Many-to-Many.png
One to One relationship mapping.

 Here two persistent classes are required to connect.


 For example, An employee having an adress. Here Employee
is a persistent class and Address is another.
 There is one to one mapping between Employee and Address
class/tables.
 In the hbm file both the classes and their corresponding tables
has to be mentioned. Attributes of class and Fields of the
tables has to be mapped accordingly.
 One extra paramter <one-to-one> or <Many-to-one with
unique=”true”> can be used to have one to one relationship.
 Trainer : Please demonstrate this to the student.
Many to One and Many to Many.

 <Many-to-One> attribute has to be used in


hbm file for many to one relationship mapping.
 <many-to-many> attribute has to be used in
hbm file for many to many relationship
mapping.
 Trainer to demonstrate these programs to
students.
Inheritance in Hibernate.

 In hibernate, inheritance classes can be mapped with databse


tables. One of the type of inheritance in Hibernate is Table per
hierachy.
 Table per hierarchy – Only one table is required for the entire
hierarchy.
 For implementing inheritance, define the base class and
derived classes with its attributes.
 In the hbm file, use the base class as the class parameter and
derived classes as subclass under base class. Syntax is given
as below.
Inheritance in hibernate

<hibernate-mapping>

<class name="Student" table="stu121" discriminator-value="stu">

<id name="id">

<generator class="increment"></generator>

</id>

<discriminator column="type" type="string"></discriminator>

<property name="name"></property>

<subclass name="Regular_Student" discriminator-value="reg_stu">

<property name="college_address"></property>

</subclass>

<subclass name="Correspondance_student" discriminator-value="corr_stu">

<property name="house_address"></property>

</subclass>

</class>
Caching in hibernate

Question : What is Caching and why do we need it / what is the


advantage of caching..
Answer : Storing the data in memory rather than querying again
and again with the database will improve the performance of the
system.
There are 3 levels of caching in hibernate.
First level cache – Session object provides the first level caching.
Deveoper need not do anything for this. Hibernate provides this
caching by default. Once the session is closed, the cached data
will be lost.
First level cache.

Pls make the image similar to this...


Second level cache.

 Second level cache is build using


SessionFactory.
 Cache parameter has to be used in hbm file for
caching the class.
 Include <cache usage="read-write"/> in the
hbm file to cache the specified class.
Query Cache.

 Query results can be cached using Query


Cache in hibernate.
 To use the query cache, parameter
hibernate.cache.use_query_cache shoudl be
set to true in configuration file.
 Use setCacheable(true) in the code to cache
the query results.
Preparation for the next module:
Please go through the XML
module we have covered and
Object Oriented concepts
Thank you!

You might also like