One-to-Many Relationships Cont.

Download Report

Transcript One-to-Many Relationships Cont.

Hibernate
Dasan Weerarathne
Introduction
 Hibernate 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 Hibernate
 Relational 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 Hibernate
 Transparent 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 Hibernate
 Support 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 Hibernate
 Database 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-toobject/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 Hibernate
 Maintenance 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 Hibernate
 Optimize 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 Hibernate
 Automatic 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
Persistence Object
Configuration File
Hibernate
Relational
Database
Mapping File
Hibernate Architecture Cont…
 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.
Creating First Hibernate App
 Before 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
Hibernate for Different Databases
 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.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
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…
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:
Second Hibernate Example
 Create new project to maintain following Book table.
 Hint: It is enough to add Book Record to the table.
Third 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
Hibernate Query Language
 HQL 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 HQL
 Full 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 HQL
 Polymorphic 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 Syntax
 Any 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
insurance_name
Car Insurance
Life Insurance
Life Insurance
Car Insurance
Dental Insurance
Life Insurance
Travel Insurance
Travel Insurance
Medical Insurance
Medical Insurance
Home Insurance
Home Insurance
Motorcycle Insurance
Motorcycle Insurance
invested_amount
1000
100
500
2500
500
900
2000
600
700
900
800
750
900
780
investement_date
2005-01-05 00:00:00
2005-10-01 00:00:00
2005-10-15 00:00:00
2005-01-01 00:00:00
2004-01-01 00:00:00
2003-01-01 00:00:00
2005-02-02 00:00:00
2005-03-03 00:00:00
2005-04-04 00:00:00
2005-03-03 00:00:00
2005-02-02 00:00:00
2004-09-09 00:00:00
2004-06-06 00:00:00
2005-03-03 00:00:00
Writing HQL Queries
 Write 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 Query
 The 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
add
The 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
createCriteria
This method is used to create a new Criteria, "rooted" at the
associated entity.
setFetchSize
This 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.
setMaxResults
This 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
Restriction.allEq
Restriction.between
Restriction.eq
Restriction.ge
Restriction.gt
Restriction.idEq
Restriction.ilike
Restriction.in
Description
This is used to apply an "equals" constraint to each property in the
key set of a Map
This is used to apply a "between" constraint to the named property
This is used to apply an "equal" constraint to the named property
This is used to apply a "greater than or equal" constraint to the
named property
This is used to apply a "greater than" constraint to the named
property
This is used to apply an "equal" constraint to the identifier property
This is case-insensitive "like", similar to Postgres ilike operator
This is used to apply an "in" constraint to the named property
Criteria Query Cont…
Method
Restriction.isNotNull
Restriction.isNull
Restriction.le
Restriction.like
Restriction.lt
Restriction.ltProperty
Restriction.ne
Restriction.neProperty
Restriction.not
Restriction.or
Description
This is used to apply an "is not null" constraint to the
named property
This is used to apply an "is null" constraint to the named
property
This is used to apply a "less than or equal" constraint to
the named property
This is used to apply a "like" constraint to the named
property
This is used to apply a "less than" constraint to the
named property
This is used to apply a "less than" constraint to two
properties
This is used to apply a "not equal" constraint to the
named property
This is used to apply a "not equal" constraint to two
properties
This returns the negation of an expression
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 Mapping
 Hibernate Support for the following relationships:
 one-to-one
 one-to-many
 many-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 Relationships
 In 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 Relationships
 In 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 Relationships
 In 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 Relationships
 A 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
relationships are often enforced
key/primary key relationships.
many-to-one
by foreign
 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….!