patni hibernate

39
Hiberna te - Freddy Gandhi

Upload: patinijava

Post on 19-May-2015

1.827 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Patni   Hibernate

Hibernate - Freddy Gandhi

Page 2: Patni   Hibernate

Patni Internal

Object Relational Mapping (ORM) The term object/relational mapping (ORM) refers to the

technique of mapping a data representation from an object model to a relational data model.

Various ORM products include :-• Apache DB Project • NET Data Objects• SimpleORM• Sybase, Inc.• Hibernate

Obtain the complete list of products from :- http://www.service-architecture.com/products/object- relational_mapping.html

Page 3: Patni   Hibernate

Patni Internal

Paradigm Mismatch

• Problem of Identity• Problem of Sub Types• Problems relating to associations• Problem of object graph navigation

Result :-

Significant waste of time and effort

Solution:-

Usage of ORM tool

Page 4: Patni   Hibernate

Patni Internal

Hibernate Features Hibernate is an object/relational mapping tool for Java

environments.

Eliminates manual data handling involved in SQL and JDBC.

Direct mapping of an object oriented solution

Provides Transparent Persistence

Data query and retrieval facilities with provisions to execute native SQL(s)

Page 5: Patni   Hibernate

Patni Internal

Benefits of using Hibernate Reduction of development time and effort otherwise spent

with manual data handling in SQL and JDBC.

Relieve the developer from 95 percent of common data persistence related programming tasks.

Object oriented solutions can be directly mapped to real world problems.No longer the mapping between the Object orient data model and relational data model is required.

ORM mapping facilitated using an XML

Higher Performance depending on usage

Open Source Project

Page 6: Patni   Hibernate

Patni Internal

Hibernate Usage Hibernate works well in a managed environment with all

major J2EE application servers, or even in standalone Java applications .

It is most useful with object-oriented Domain Model and business logic in the Java-based middle-tier.

Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database.

Hibernate is most suitable for applications based on a rich Domain Model involving complex interaction between entities

Page 7: Patni   Hibernate

Hibernate Setup

Page 8: Patni   Hibernate

Patni Internal

Installation Download the latest version of Hibernate(e.g. hibernate-

3.0.5.zip) from the site http://www.hibernate.org

The zip file will contain the Hibernate jar (along with other third party jar files for various features like logging,connection pooling), template of configuration files and source code of example applications implemented using Hibernate

Set the class path to include the necessary jar files and the configuration files

Page 9: Patni   Hibernate

Patni Internal

Configuration Files Hibernate uses 3 configuration files during runtime, these

files need to be present in its Class path :-

hibernate.cfg.xml : Configuration of properties (both related and not related to Hibernate).Contains the ORM Mapping file names

hibernate.properties : Configuration of properties (both related and not related to Hibernate).

Application.hbm.xml :This is the ORM mapping file corresponding to your application.The name of this file is defined by the developer (mapping is done in the hibernate.cfg.xml ), e.g. Event.hbm.xml.There can be more than one file like this for the same application

Page 10: Patni   Hibernate

Patni Internal

hibernate.cfg.xml

• Example <hibernate-configuration> <session-factory> <property name= connection.datasource">java:comp/env/jdbc/quickstart </property> <property name="show_sql">false</property> <property name="dialect">org.hibernate.dialect.PostgreSQLDialect </property>

<!-- Mapping files --> <mapping resource="Cat.hbm.xml"/> </session-factory></hibernate-configuration>

Page 11: Patni   Hibernate

Patni Internal

hibernate.cfg.xml Hibernate XML-based configuration.to know the the JDBC

connection parameter(the other approach being the properties file)

A SessionFactory is Hibernate's concept of a single datastore, multiple databases can be used by creating multiple XML configuration files and creating multiple Configuration and SessionFactory objects in your application.

The element (resource mapping ) provides the name of the ORM mapping file(s) for the persistent classes of the application

Page 12: Patni   Hibernate

Patni Internal

hibernate.properties

• Please find the attached template of the property file

hibernate.properties

Page 13: Patni   Hibernate

Patni Internal

Application.hbm.xml

• Example<hibernate-mapping><class name="Event" table="EVENTS">

<id name="id" column="EVENT_ID"></id><property name="date“

type="timestamp"column="EVENT_DATE"/><property name="title"/>

</class><class name=“Person" table=“PERSON">….</class></hibernate-mapping>

Page 14: Patni   Hibernate

Exercise 1 & Exercise 2

Page 15: Patni   Hibernate

Working with Hibernate

Page 16: Patni   Hibernate

Patni Internal

Core Interfaces

Configuration Interface:The application uses the configuration instance to specify the location of the mapping documents and Hibernate-specific properties and then create the SessionFactory

SessionFactory Interface: A SessionFactory is an expensive-to-create,thread safe object intended to be shared by all application threads.It is created once, usually on application startup, from a Configuration instance.

Session Interface: A single-threaded, short-lived object representing a conversation between the application and the persistent store.

Page 17: Patni   Hibernate

Patni Internal

Core Interfaces

Transaction Interface: Optional interface to manage transactions.Hibernate applications may choose not to use this interface, instead manage transactions through their infrastructure code.

Query Interface : This allows the developer to perform queries against the database and control how the query is executed

Page 18: Patni   Hibernate

Patni Internal

States of an Instance Instances(of Persistent Classes) may exist in one of three

states:• Transient :The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value).

•Persistent :The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context

•Detached :The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corresponding row in the database.For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity.

Page 19: Patni   Hibernate

Patni Internal

States of an Instance

Example:Session session = HibernateUtil.currentSession();Transaction tx = session.beginTransaction();Person aPerson = (Person) session.load(Person.class, personId);Event anEvent = (Event) session.load(Event.class, eventId);tx.commit();HibernateUtil.closeSession();aPerson.getEvents().add(anEvent); // aPerson is detachedSession session2 = HibernateUtil.currentSession();Transaction tx2 = session.beginTransaction();session2.update(aPerson); // Reattachment of aPersontx2.commit();HibernateUtil.closeSession();

Page 20: Patni   Hibernate

Basic O/R Mapping

Page 21: Patni   Hibernate

Patni Internal

Basic O/R Mapping Object/relational mappings are defined in an XML

document.

The mapping language is Java-centric, meaning that mappings are constructed around persistent class declarations, not table declarations.

A number of tools exist to generate the mapping document, including XDoclet, Middlegen and AndroMDA.

Page 22: Patni   Hibernate

Patni Internal

Element <hibernate-mapping> The root element in O/R mapping file.Contains the

following attributes

•schema (optional): The name of a database schema.•catalog (optional): The name of a database catalog.•default-cascade (optional - defaults to none): A default cascade style.•package (optional): Specifies a package prefix to assume for unqualified class names in the mapping document.

Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)

Page 23: Patni   Hibernate

Patni Internal

Element <class> You may declare a persistent class using the class element:

•name (optional): The fully qualified Java class name of the persistent class (or interface). If this attribute is missing, it is assumed that the mapping is for a non-POJO entity.• table (optional - defaults to the unqualified class name): The name of its database table.•mutable (optional, defaults to true): Specifies that instances of the class are (not) mutable.

Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)

Page 24: Patni   Hibernate

Patni Internal

Element <id> Mapped classes must declare the primary key column of

the database tab:

•name (optional): The name of the identifier property.•type (optional): A name that indicates the Hibernate type.• column (optional - defaults to the property name): The name of the primary key column.

There is an alternative <composite-id> declaration to allow access to legacy data with composite keys

Get the complete list and more information on the

attributes from Hibernate_reference.pdf(Basic O/R Mapping)

Page 25: Patni   Hibernate

Patni Internal

Element <property> Mapped classes must declare the primary key column of

the database tab:

•name: the name of the property, with an initial lowercase letter.•column (optional - defaults to the property name): the name of the mapped database table column. This may also be specified by nested <column> element(s).• type (optional): a name that indicates the Hibernate type.

Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)

Page 26: Patni   Hibernate

Collections & Associations

Page 27: Patni   Hibernate

Patni Internal

Collection Hibernate supports all kinds of collection mappings, a <set>

being most common.

The other collection mapping include <list>, <map>, <bag> and <array>

Collection instances are distinguished in the database by the foreign key of the entity that owns the collection.For a many-to-many association(or n:m entity relationship), an association table is needed. This foreign key is referred to as the collection key column (or columns) of the collection table. The collection key column is mapped by the <key> element.

Page 28: Patni   Hibernate

Patni Internal

Collection Mapping• Example :

<class name="Department" table="DEPARTMENT"><id name="id" column="DEPCODE"><generator class="increment"/></id>

<property name="DeptName" column="DNAME"/><set name="EMPLIST">

<key column="DEPCODE"/><one-to-many column = "DEPTID"

class="Employee"/></set>

</class>

Page 29: Patni   Hibernate

Patni Internal

Associations Associations refer to relationships between entities

Using Hibernate, we can represent relationships of all cardinality,i.e. one-to-one, one-to-many,many-to-one and many-to-many

A many-to-many association will result in a link or association table

Hibernate supports polymorphic association

Page 30: Patni   Hibernate

Exercise 3

Page 31: Patni   Hibernate

HQL(Hibernate Query Language)

Page 32: Patni   Hibernate

Patni Internal

HQL(Hibernate Query Language)• Hibernate is equipped with an extremely powerful query

language that (quite intentionally) looks very much like SQL

• HQL is fully object-oriented, understanding notions like inheritance,polymorphism and association.

• Queries are case-insensitive, except for names of Java classes and properties.

• HQL isn’t a data-manipulation language like SQL.It is used only for object retrieval and not for updating,inserting or deleting data.Object state synchronization is the work of the persistence manager.

Page 33: Patni   Hibernate

Patni Internal

HQL example 1 E.g. Get a list of all the employees (Table :

MASTER_EMPLOYEE)

SQL :- select * from MASTER_EMPLOYEE EMP

HQL :- from MASTER_EMPLOYEE EMP

Programmatically :- Query q = session.createQuery(“from

MASTER_EMPLOYEE EMP ”) ; List result = q.list();

Page 34: Patni   Hibernate

Patni Internal

HQL example 2• E.g. Get a list of all the employees (Table :

MASTER_EMPLOYEE) where D_CODE = ’00A’

• SQL :- select * from MASTER_EMPLOYEE EMP where EMP.D_CODE = ’00A’

HQL Programmatically :- Query q = session.createQuery(“from

MASTER_EMPLOYEE EMP where EMP.D_CODE = :code ”) ;

q.setString(“code”,”00A”); List result = q.list();

Page 35: Patni   Hibernate

Patni Internal

HQL example 3• E.g. Get a count of all the employees• SQL :- select count(*) from MASTER_EMPLOYEE EMP

HQL Programmatically :- Query q = session.createQuery(“select count(*) from

MASTER_EMPLOYEE EMP”) ; List result = q.list();

The List(result) returned in the above case will contain single object of the Integer Class.Incase of functions like avg() the object will be of Float Class

The supported aggregate functions are avg(...), sum(...), min(...), max(...) count(*) count(...), count(distinct ...), count(all...)

Page 36: Patni   Hibernate

Patni Internal

HQLHQL provides several other features for data

retrieval which include :-

• Sub querying•Join types supported by ANSI SQL (e.g. inner join,left outer,etc)•Polymorphic queries•Ordering/groping•Usage of Expressions [e.g. emp.name in ( ‘Rakesh', ‘Manish', ‘Dhiraj' )]•Executing native SQL queries•Using stored procedures for querying

Refer to hibernate_reference.pdf(Chapters : HQL,Criteria Query,Native SQL)

Page 37: Patni   Hibernate

Patni Internal

Appendix• ThreadLocal : Each thread that accesses one (via its get or set method) has its own,

independently initialized copy of the variable. ThreadLocal objects are typically private static variables in classes that wish to associate state with a thread (Transaction ID).

• Domain Model: An object model of the domain problem that incorporates both

behavior and data[BACK]

Page 38: Patni   Hibernate

Patni Internal

Appendix• Transparent Persistence In object-relational mapping products, the ability to directly

manipulate data stored in a relational database using an object programming language is called transparent persistence

[BACK]

• Persistent classes Classes in an application that implement the entities of the business

problem (e.g. Customer and Order in an E-commerce application)

[BACK]

Page 39: Patni   Hibernate

Patni Internal

References

URL• www.hibernate.org

Reference Material•hibernate_reference.pdf(can be downloaded from the

above site)

•Hibernate in Action(Christian Bauer & Gavin King)

[Incase of any doubts or queries about this

presentation mail me at [email protected]]