Hibernate
description
Transcript of Hibernate
Hibernate
Dasan Weerarathne
IntroductionHibernate allows to persist the java objects
using its’ Object/Relational Mapping (ORM) framework.
It is automates ORM and considerably reduces the number of lines of code needed to persist the object in the database.
Hibernate can be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans.
Advantages of Using HibernateRelational Persistence for JAVA
Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there is mismatch between how data is represented in objects versus relational database.
JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema
Hibernate is flexible and powerful ORM solution to map Java classes to database tables.
Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
Advantages of Using HibernateTransparent Persistence
The automatic mapping of Java objects with database tables.
Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. (With JDBC this conversion is to be taken care of by the developer manually with lines of code. )
Advantages of Using HibernateSupport for Query Language
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database.
Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries.
Hibernate also selects an effective way to perform a database manipulation task for an application.
Advantages of Using HibernateDatabase Dependent Code
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table.
Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.
Advantages of Using HibernateMaintenance Cost
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.
Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
Advantages of Using HibernateOptimize Performance
Caching is retention of data, usually in application to reduce disk access.
Hibernate, with Transparent Persistence, cache is set to application work space.
Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.
(With JDBC, caching is maintained by hand-coding)
Advantages of Using HibernateAutomatic Versioning and Time Stamping
By database versioning one can be assured that the changes done by one person is not being roll backed by another one unintentionally.
Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate.
(In JDBC there is no check that always every user has updated data.
This check has to be added by the developer)
Disadvantages of Hibernate Steep learning curve.
Use of Hibernate is an overhead for the applications which are :Simple and use one database that never change Need to put data to database tables, no further SQL
queries There are no objects which are mapped to two different
tables
(Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best choice.)
Disadvantages of Hibernate Anybody wanting to maintain application
using Hibernate will need to know Hibernate.
For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion.
Hibernate does not allow some type of queries which are supported by JDBC.
Hibernate Architecture
Application
Hibernate
Relational Database
Configuration File
Mapping File
Persistence Object
To use Hibernate, it is required to create Java classes that represents the table in the database and then map the instance variable in the class with the columns in the database.
Then Hibernate can be used to perform operations on the database like select, insert, update and delete the records in the table.
Hibernate automatically creates the query to perform these operations.
Hibernate Architecture Cont…
Hibernate architecture has three main components:
Connection Management: Hibernate Connection management service provide efficient
management of the database connections. Database connection is the most expensive part of interacting
with the database as it requires a lot of resources of open and close the database connection.
Transaction Management: Transaction management service provide the ability to the user
to execute more than one database statements at a time.
Hibernate Architecture Cont…
Object Relational Mapping : Object relational mapping is technique of mapping the
data representation from an object model to a relational data model.
This part of the hibernate is used to select, insert, update and delete the records form the underlying table.
When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query.
Hibernate Architecture Cont…
Hibernate Architecture Cont…
SessionFactory (org.hibernate.SessionFactory)A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level.
Session (org.hibernate.Session)A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.
Hibernate Architecture Cont…
Transaction (org.hibernate.Transaction)A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction, is never optional!
ConnectionProvider (org.hibernate.connection.ConnectionProvider)A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer.
Hibernate Architecture Cont…
TransactionFactory (org.hibernate.TransactionFactory)A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer.
Hibernate Architecture Cont…
Creating First Hibernate AppBefore you start coding you have to download
Hibernate Framework from the following URL. http://olex.openlogic.com/packages/hibernate#package_detail_tabs
Create Database “vtshibernate” and Create table “contact” at the MySQL database.
First Hibernate App Cont…Create Java Project using E-clips
“FirstHibernateProject”Create package under the src directory.
(com.virtusa.contact)Create hibernate.cfg.xml under the src
folder.Create contact.hbm.xml under the src
folder.Add doc type URL for both .xml files.
First Hibernate App Cont…Completed hibernate.cfg.xml
DB2 - org.hibernate.dialect.DB2Dialect HypersonicSQL - org.hibernate.dialect.HSQLDialect Informix - org.hibernate.dialect.InformixDialect Ingres - org.hibernate.dialect.IngresDialect Interbase - org.hibernate.dialect.InterbaseDialect Pointbase - org.hibernate.dialect.PointbaseDialect PostgreSQL - org.hibernate.dialect.PostgreSQLDialect Mckoi SQL - org.hibernate.dialect.MckoiDialect Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect MySQL - org.hibernate.dialect.MySQLDialectMySQL - org.hibernate.dialect.MySQLDialect Oracle (any version) - org.hibernate.dialect.OracleDialect Oracle 9 - org.hibernate.dialect.Oracle9Dialect Progress - org.hibernate.dialect.ProgressDialect FrontBase - org.hibernate.dialect.FrontbaseDialect SAP DB - org.hibernate.dialect.SAPDBDialect Sybase - org.hibernate.dialect.SybaseDialect Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect
Hibernate for Different Databases
First Hibernate App Cont…Completed contact.hbm.xml
First Hibernate App Cont…<hibernate-mapping>
First Hibernate App Cont…<class>
First Hibernate App Cont…
First Hibernate App Cont…
<id>
First Hibernate App Cont…
< generator> There are shortcut names for the built-in
generators as shown below:
First Hibernate App Cont…
< property >
First Hibernate App Cont…
First Hibernate App Cont…
Create the Java class called Contact having getters and setters:
First Hibernate App Cont…
Create Test Class to Insert new Record to the Database:
First Hibernate App Cont…
Your Final Project Should appear as below:
First Hibernate App Cont…
Create new project to maintain following Book table.Hint: It is enough to add Book Record to the
table.
Second Hibernate Example
Create new project to maintain Insurance Information:Hit: The program should provide functionality
to add Insurance Information and also should provide functionality to modify the given Insurance information.
Now Modify the program to delete a given insurance Information
Third Hibernate Example
Hibernate Query LanguageHQL is much like SQL and are case-
insensitive, except for the names of the Java Classes and properties.
Hibernate Query Language is used to execute queries against database.
Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application.
HQL is based on the relational object models and makes the SQL object oriented.
Hibernate Query Language uses Classes and properties instead of tables and columns.
Advantage of using HQLFull support for relational operations:
HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns
Return result as Object:The HQL queries return the query result(s) in the form of object(s), which is easy to use. This eliminates the need of creating the object and populate the data from result set.
Advantage of using HQLPolymorphic Queries:
HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any.
Support for Advance features:HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.
Understanding HQL SyntaxAny Hibernate Query Language may consist of following elements:
Clauses (from, select, where, order by, group by)Aggregate functions (avg, min, max, sum, count)Sub queries (query within another query)
Create following Data Set
ID insurance_name invested_amount investement_date
1 Car Insurance 1000 2005-01-05 00:00:00
2 Life Insurance 100 2005-10-01 00:00:00
3 Life Insurance 500 2005-10-15 00:00:00
4 Car Insurance 2500 2005-01-01 00:00:00
5 Dental Insurance 500 2004-01-01 00:00:00
6 Life Insurance 900 2003-01-01 00:00:00
7 Travel Insurance 2000 2005-02-02 00:00:00
8 Travel Insurance 600 2005-03-03 00:00:00
9 Medical Insurance 700 2005-04-04 00:00:00
10 Medical Insurance 900 2005-03-03 00:00:00
11 Home Insurance 800 2005-02-02 00:00:00
12 Home Insurance 750 2004-09-09 00:00:00
13 Motorcycle Insurance 900 2004-06-06 00:00:00
14 Motorcycle Insurance 780 2005-03-03 00:00:00
Writing HQL QueriesWrite HQL Query to View all the available data at the table.Write a HQL query to get total count of the all the records.
Write a HQL query to get count of the insurance based on the Amount.
Writing HQL Queries Cont…Write a HQL query to get count of the insurance based on the
Insurance Name.
Write HQL query to get the Avg/Max/Min of the total Amounts.
Criteria QueryThe interface org.hibernate.Criteria represents a query against a particular
persistent class. The Session is a factory for Criteria instances. An individual query criterion is an instance of the interface
org.hibernate.criterion.Criterion. The class org.hibernate.criterion.Restrictions defines factory methods for
obtaining certain built-in Criterion types.Ref:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html
Criteria Query Cont…Criteria Interface provides the following
methods
Method Description
addThe Add method adds a Criterion to constrain the results to
be retrieved.
addOrder Add an Order to the result set.
createAlias Join an association, assigning an alias to the joined entity
createCriteriaThis method is used to create a new Criteria, "rooted" at the
associated entity.
setFetchSizeThis method is used to set a fetch size for the underlying
JDBC query.
setFirstResult This method is used to set the first result to be retrieved.
setMaxResultsThis method is used to set a limit upon the number of objects
to be retrieved.
uniqueResult
This method is used to instruct the Hibernate to fetch and return the unique records from database.
Criteria Query Cont…Class Restriction provides built-in
criterion via static factory methods
Method DescriptionRestriction.allEq
This is used to apply an "equals" constraint to each property in the
key set of a MapRestriction.between
This is used to apply a "between" constraint to the named property
Restriction.eq
This is used to apply an "equal" constraint to the named property
Restriction.ge
This is used to apply a "greater than or equal" constraint to the named property
Restriction.gt
This is used to apply a "greater than" constraint to the named property
Restriction.idEq This is used to apply an "equal" constraint to the identifier propertyRestriction.ilike
This is case-insensitive "like", similar to Postgres ilike operator
Restriction.in This is used to apply an "in" constraint to the named property
Criteria Query Cont…
Method Description
Restriction.isNotNullThis is used to apply an "is not null" constraint to the
named property
Restriction.isNull This is used to apply an "is null" constraint to the named
property
Restriction.le This is used to apply a "less than or equal" constraint to
the named property
Restriction.likeThis is used to apply a "like" constraint to the named
property
Restriction.ltThis is used to apply a "less than" constraint to the
named property
Restriction.ltPropertyThis is used to apply a "less than" constraint to two
properties
Restriction.ne This is used to apply a "not equal" constraint to the
named property
Restriction.nePropertyThis is used to apply a "not equal" constraint to two
propertiesRestriction.not This returns the negation of an expression
Restriction.or This returns the disjuction of two expressions
Criteria Query Cont…Criteria Query Exercises 01:
Create Sample program to display Insurance records which are having Amount in-between 1000 and 2500.
(Make sure that you should display maximum only 5 records)Criteria Query Exercises 02:
Create sample program to return Insurance records which are having investment date in-between 2005/01/01 to 2005/03/03.
(Make sure that you should display maximum only 5 records)
Hibernate Relationship MappingHibernate Support for the following relationships:
one-to-oneone-to-manymany-to-many many-to-one
We can simulate the all these relationships in our Java. With the help of Hibernate relationships we can define these
associations among the persistence unit and use in the Java program
One-to-One RelationshipsIn case of one-to-one relationships, each row in
table A linked to only one row in table B. Here we will implement one-to-one relationship between two entries Employee and EmployeeAddress.
We are using two tables employee and employee_address and java entities Employee and EmployeeAddress maps respectively.
One-to-One Relationships Cont.ER Diagram For the Relationship:
One-to-One Relationships Cont.Employe.hmb.xml:
One-to-One Relationships Cont.EmployeAddress.hmb.xml:
One-to-One Relationships Cont.Driver Program:
One-to-Many RelationshipsIn case of one-to-many relationships, each row in table
A linked to multiple rows in table B.
Here we will implement one-to-many relationship between two entries Group and Story. There exists multiple stories under a group.
We are using two tables grouptable and story and java entities Group and Story maps respectively.
One-to-Many Relationships Cont.
ER Diagram For the Relationship:
One-to-Many Relationships Cont.
Group.hmb.xml:
One-to-Many Relationships Cont.
Story.hmb.xml:
One-to-Many Relationships Cont.
Driver Program:
One-to-Many Relationships Cont.
Display Stories for a given Group Id:
Many-to-Many RelationshipsIn case of many-to-many relationships, each row in table
A linked to multiple rows in table B and vice versa.
Here we will implement many-to-many relationship between two entries Author and Book.
A book might be authored by multiple author and one author might author many books.
We are using two tables author and book and java entities Author and Book maps respectively.
Many-to-Many Relationships Cont
ER Diagram For the Relationship:
Many-to-Many Relationships Cont
Author.hmb.xml:
Many-to-Many Relationships Cont
Book.hmb.xml:
Many-to-Many Relationships Cont
Driver Program:
Many-to-Many Relationships Cont
Displaying Book Information for a given Author:
Many-to-One RelationshipsA many-to-one relationship is where one entity contains
values that refer to another entity (a column or set of columns) that has unique values.
In relational databases, these many-to-one relationships are often enforced by foreign key/primary key relationships.
Here we will implement Many-to-one relationship between two entries Group and Story. (Example Used under the topic One-to-Many)
Many-to-One RelationshipsCont.
Many-to-One Relationships Cont.
In the Entity Story.java we have to define Group object and getter and setters for the same.
Many-to-One Relationships Cont.
Modified Story.hmb.xml:
Many-to-One Relationships Cont.
The below code will load the Story entity whose primary key is 4, and then retrieved the parent Group.
Thank You….!