Transcript Hibernate
Hibernate 1
Introduction – ORM, Helloworld
Application
Enterprise computing
Reality of today’s enterprise computing
Modern programming languages (Java)
Intuitive, object-oriented view of the application level business
entities
Enterprise data (underlying data entities)
Relational databases
Gap between the two is one of the hard facts of enterprise
computing today.Hibernate takes up the challenge to provide
a bridge between relational data and Java objects.
ORM Introduction [1]
What is ORM (Object Relational Mapping) ?
ORM is a programming technique for converting data between
incompatible systems
From relational databases (e.g.Oracle, MySQL) to object oriented
(OO) programming languages (e.g. Java) and back
ORM can be viewed as the automated and transparent persistence
of objects in a Java application to the database tables in an
RDBMS using metadata that describes the mapping between the
objects and the database
ORM Introduction [2]
Data management tasks in OO
languages are implemented by
manipulating objects that are
non-scalar values.
Many relational database
products can only store and
manipulate scalar values such
as integers and strings in
normalized tables
The programmer must convert
the object values into groups of
simpler values for storage in the
database (and convert them
back on retrieval) or
Use only simple scalar values
within the program
– ORM solutions use the first
approach
– The crux of the approach is
translating the objects to forms
that can be stored in the
database for easy retrieval,
while preserving the properties
of the objects and their
relationships. These objects
are referred to as persistent
objects
– ORM often reduces the
amount of code that needs to
be written.
Advantages of ORM
Lets business code access
objects rather than database
tables
Hides details of SQL queries
from OO logic
‘JDBC’ under the hood
No need to deal with database
implementation, only deal with
domain objects
Entities based on business
concept rather than on
business structure
Transaction management
Fast development of application
Faster maintenance and
refactoring
Popular ORM options for Java
Enterprise Java Beans (Entity
Beans)
Java Data Objects
Castor
TopLink
Spring DAO
Hibernate etc.,
Introduction to Hibernate
Hibernate details
Hibernate is an ORM library for
the Java language, providing a
framework for mapping an
object oriented domain model
to a traditional relational
database
Hibernate is free software
distributed under the GNU
Lesser General Public License
Hibernate's primary feature is
mapping from Java classes to
database tables (and from Java
data types to SQL data types).
Hibernate also provides data
query and retrieval facilities.
Hibernate generates the SQL
calls and relieves the developer
from manual result set handling
and object conversion.
This keeps the application
portable to all supported SQL
databases, with database
portability delivered with very
little performance overhead.
We will do a dive into a
Hibernate project to understand
the concepts rather than
studying too much theory …
Hibernate in a Java application
POJO = Plain Old
Java Objects. The
java business
domain classes.
Hibernate_config_example
Client code
Hibernate XML
configuration file that
points to the
database(s) and the
XML mapping files
POJOs
Hibernate System boundary
Configuration
Hibernate
Mappings
JDBC
Example of mapping
DATABASE
XML Mapping files
that tell hibernate
which objects
(POJOs) relate to
which database
tables
HelloWorld application
HelloWorld
HelloWorld application
Development process decides how
the Hibernate toolset will be used.
•
Is a very simple application
used to demonstrate basic
concepts
We will do this through setting
up project infrastructure for a
plain Java application that
integrates Hibernate
Details of how Hibernate
could be configured in such
an environment is shown
•
•
installed
Ant scripts are used to
compile and run the project.
Hibernate tools can also be
used from within Ant
It is important to prepare the tools
and decide on the development
process before starting on a real
Hibernate project.
In addition to Ant, it is necessary to
have a relational database installed
as the persistent store. MySQL is
used in the example.
•
Ant tool is required to be
•
For example, Hibernate toolset can
be used to export database
schemas automatically.
The JDBC driver for MySQL need to
be downloaded and available for use
The Hibernate libraries have to be
downloaded from
http://www.hibernate.org/ and
unpacked..
Hibernate project setup
Hibernate project setup
Prerequisites
There are a number of jar files in the lib
directory
•
Downloads / installs
Production release of
Hibernate from their website
Apache Ant to be installed on
the development machine
A database installed on the
development machine with
the JDBC driver of it also
downloaded and available
•
•
Create a work directory
anywhere on your development
machine
For our example it is
“D:\Official\Company\Training
\Hibernate\antprojects\hellow
orld” (referred to as
WORKDIR)
Create lib and src
subdirectories within
WORKDIR
•
Most of them are from the hibernate
distribution. mysql-connector-java-5.1.12bin.jar is the JDBC driver for the MySQL
database and is not from the hibernate
distribution.
Some jar files that are here may not be
required for your particular version of
Hibernate Or you may need some other
jar files.
To make sure that you have the right set of
libraries, always check the README.txt in
the Hibernate distribution package. This
contains an up to date list of all required
and optional third-party libraries for
Hibernate. One needs the libraries listed
as required for runtime.
In the “Hello World” application you want
to store messages in the database and
load them from the database.
Libraries required for
using Hibernate
Integrating hibernate
To integrate hibernate, one will need
to use several Java libraries
The Java Archive (JAR ) file for your
JDBC driver, which you will need to
find for your specific relational
database
Hibernate download does not
include any JDBC drivers. You must
obtain them yourselves.
The database provider may provide
these as a separate download
Or they may be bundled with the
database installation
–
The next step is to deploy the
appropriate jar file (we are using
hibernate-core-4.0.1.Final.jar) with
your application. This file is
provided with the Hibernate binary
distribution in the lib/required
subdirectory.
–
Beyond this, several libraries are
required for hibernate. These are
included in the lib directory of the
Hibernate installation.
The domain model
Domain model
Create the domain model
Hibernate applications define
persistent classes that are
mapped to the database tables.
Classes are defined based on
analysis of the business
domain, hence they are
referred to as a domain
model.
The HelloWorld example has
one class and its mapping.
Its objective is to store
messages in a database and
retrieve them for display.
Create Message.java and
store it in the src folder into a
directory called hello.
Message class
•
•
•
Has three attributes – identifier, message
text and a reference to another Message
object.
All attributes of the Message class have
Javabean style property accessor (get)
methods. The class has a constructor with
no parameters. The no-argument
constructor is a requirement (Hibernate
uses reflection on the constructor to
instantiate objects)
Instances of the Message class can be
managed (made persistent) by Hibernate,
but they don’t have to be. Because the
Message object does not implement any
Hibernate specific classes or interfaces,
you can use it just like any other Java
class.
Hibernate mappings
Mapping files
Mapping files tell Hibernate which
tables relate to which objects. This
information is typically provided in
XML mapping file(s).
This tells Hibernate how to load and
store objects of the persistent class,
what table in the database it has to
access, and what columns in that
table it should use
One has to create and associate a
small, clear mapping file with each
of the POJOs that one wishes to
map to the database. A single
monolithic configuration file can also
be used, but is discouraged
–
The XML file is much easier to
modify than a complex population of
a POJO from a result set. If the
mappings change, it is much easier
to change an XML file
–
If you are starting a new application,
you need to create the schema,
POJOs and the mapping files.
–
Hibernate makes available tools
where one can generate the
database directly from the mapping
files.
Mapping the class to a
database schema
Mapping class to a database
schema
Prerequisite for object /
relational mapping magic to
occur. Hibernate needs more
information about how the
Message class should be
persisted
Hibernate needs to know how
instances of that class are to
be stored and loaded from the
database.
This metadata can be written
into an XML mapping
document which defines, how
properties of the Message
class map to columns of a
MESSAGE table.
Message class mapping
• The mapping document is a file
called Message.hbm.xml with
the content as shown above.
• It is placed next to the
persistent class file
Message.java in the source
package hello.
• hbm suffix is a naming
convention accepted by the
Hibernate community and most
developers prefer to place
mapping files next to the
source code of the domain
class.
Storing and loading objects
Driver program
Contains main() class for
storing and loading objects
HelloWorld application code
The Hibernate Session, Transaction
and Query interfaces are called to
access the database
• Session – A Hibernate session is a
single threaded nonshared object
that represents a particular unit of
work with the database. It has the
persistence manager API you call to
load and store objects.
This code is placed in the hello
directory along with the
Message persistent class.
This class has a java main()
method, that can be called from
the command line directly.
Inside the application, you
execute a number of units of
work with Hibernate.
The first unit stores a new
Message object, and the
second unit loads all objects
and prints their text to the
console.
• Transaction – This Hibernate API
•
can be used to set transaction
boundaries programmatically, but it
is optional; Other choices are JDBC
transactions demarcation, the JTA
interface, or container-managed
transactions with EJBs
Query – A database query can be
written in Hibernate’s own objectoriented query language (HQL) or
plain SQL. This interface allows you
to create queries, bind arguments to
place holders in the query and
execute the query in many ways.
Where does Hibernate fit in
your java application ?
Possible ways of using
hibernate
Call hibernate directly from your java
application
Access hibernate through another
framework. Hibernate can be called
from a Swing application, a servlet,
a portlet, a JSP page, or any other
java application that has access to a
database
Hibernate is used to create a data
access layer for an application or
replace an existing data access
layer
–
Regardless of the environment , one
needs to one has to define the
Configuration details, that is
represented by the Configuration
object
–
From the Configuration object a
single SessionFactory object is
created
–
From SessionFactory, Session
objects are instantiated, through
which your application accesses
Hibernate’s representation of the
database
Session Factory
SessionFactory
Session objects are created
from SessionFactory
using openSession() , method
(4 variants are available)
Session
Session objects manage
connection data, caching and
mappings.
User application is responsible for
managing the SessionFactory.
One SessionFactory object is
required per database instance
connected through Hibernate. It is
possible to retrieve metadata and
statistics from the SessionFactory.
close() method is used on
SessionFactory to release all
resource information used by
the session factory and made
available to the session
objects. Related Session
objects have to be closed
before invoking this to close
the session
factory.