Hibernate – Object Relation Mapper -Gopal Patel
CONFIDENTIAL
1
Agenda
Introduction to different ways of persisting data Object relation mapping fundamentals Hibernate Architecture Hibernate Environment Hibernate Round Trip development Features of hibernate RDBMS Support Tools support References to get started Project Architecture & Hibernate layer in Application Examples in depth CONFIDENTIAL
2
Introduction to different ways of persisting data Without Databases
Object Serialization
Uses the file system for storing the serialized object forms. Not a object relation mapping technique. Only accessible through java language. Bad choice for storing enterprise data.
With Databases (RDBMS )
JDBC
Entity Beans (BMP and CMP)
EJB require a one-to-one mapping to database tables Requires application server supporting EJB Container
JDO
Simply provide API accessing database, No object relation mapping technique Database dependent code
Commercial from individual vendors. Mappings not standard
O/R Mapping tool like Hibernate
Rich features with total abstraction to databases. Provides resolutions to majority concerns on OR mapping.
CONFIDENTIAL
3
Object relation mapping fundamentals
Objects to integrate into Relational model Object modeling describes system through objects, Association, behavior, state, inheritance Relational modeling describes system through information. Relation, Attribute, Domain Object-relational mapping is the process of transforming between object and relational modeling approaches
CONFIDENTIAL
4
Object Relation Mapping Advantages
No more SQL/JDBC CRUD hand coded operations. Natural programming model (OODBMS) Reduced Line Of Code Code can be run / Tested out side the container (Will see) Classes may be reused in non persistence context Minimum database access with smart fetching strategies Opportunities for aggressive caching Structural mapping more robust when Object/Relational data model changes.
CONFIDENTIAL
5
Hibernate Architecture Responsibilities of architecture -Manage
connection with the database -Converts HQL (Hibernate Query Language) statements to database specific statement. -Manage result set on its own. -Performs mapping of these database specific data to Java objects which are directly used by Java application.
CONFIDENTIAL
6
Hibernate Architecture Elements
CONFIDENTIAL
7
Hibernate Architecture – Core Interfaces
Hibernate Core interfaces
Session interface
SessionFactory Interface
Hibernate session can be termed as a collection of loaded objects relating to a single unit of work. This Is the primary interface used by the Hibernate application. Hibernate Session are not thread safe hence by design be used one session per thread.
Hibernate Session provider Single instance per application/data source. Caches generated SQL statements and other mapping metadata.
Configuration Interface
The Configuration object is used to configure and bootstrap Hibernate. Application uses Configuration instance to specify the location of mapping files.
CONFIDENTIAL
8
Hibernate Architecture - Core Interfaces
Transaction Interface
Query and Criteria Interfaces.
The Transaction interface is an optional API. User might choose to use JDBC Tx, JTA Abstracts the application code by the underlying transaction implementations. Helps to keep hibernate application portable between different kind of execution environments.
Manages and controls query execution Queries can be written in HQL or in native SQL. Criteria interfaces allows you to create execute object oriented criteria queries.
Callback interfaces
Allow the application to receive notification when a transaction happens to an object. Eg. when the object is loaded, deleted, saved. Hibernate interfaces are not needed to be implemented but are useful sometimes.
Types
Extension Interfaces
Interfaces that allow extension of Hibernate’s powerful mapping functionality, such as UserType, CompositeUserType, and IdentifierGenerator.
CONFIDENTIAL
9
Hibernate Architecture Elements
General steps: /* Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files. */ Configuration cfg = new Configuration(); cfg.configure(CONFIG_FILE_LOCATION);
/* Create session factory from configuration object */ SessionFactory sessionFactory = cfg.buildSessionFactory();
/* Get one session from this session factory. */
Session session = sessionFactory.openSession();
/* Create HQL query. */ Query query = session.createQuery("from EmployeeBean”);
/* Execute query to get list containing Java objects. */ List<EmployeeBean> finalList = query.list(); CONFIDENTIAL
10
Hibernate Environment Lib - antlr.jar - cglib-full.jar - asm.jar - asm-attrs.jar - commons-collection.jar - commons-logging.jar - ehcache.jar - hibernate3.jar - jta.jar - dom4j.jar - log4j.jar
CONFIDENTIAL
11
Hibernate Environment Hibernate configuration property file
Used for configuring hibernate configuration
Contains - Database Configuration - Datasource Configuration - Transaction Configuration - Caching Configuration - ConnectionPool Configuration - Other Settings.
CONFIDENTIAL
12
Hibernate Environment The hibernate-mapping configuration file
Object to relation mappings are often defined in a xml file
Easy mapping file can be hand written or edited.
Java Centric persistence classes.
No of tools available to generate the configuration. -AndroMDA -XDoclets -Middlegen
Standard DTD for correct implementation
CONFIDENTIAL
13
Hibernate Round Trip development Hibernate Configuration
CONFIDENTIAL
14
Hibernate Round Trip development Employee Java Object
“Employee” DB Table
Column
|
Type
| Modifiers
----------+-----------------------+--------EMPID (PK) |
int
| not null
name
|
varchar(50)
| not null
salary
|
double
|
email
|
varchar(50)
|
CONFIDENTIAL
15
Hibernate Round Trip development
Hibernate XML Configuration Employee.hbm.xml
CONFIDENTIAL
16
Hibernate Round Trip development
Persisting the Employee SessionFactory sf = Configuration.configure().buildSessionFactory(); Session session = sf.OpenSession(); Transaction tx = session.beginTransaction();
Employee emp = new Employee() emp.setEmail(“
[email protected]”); emp.setName(“Gopal Patel”); emp.setSalary(“121”); session.save(emp); Tx.commit(); session.close();
CONFIDENTIAL
17
Hibernate Round Trip development
Loading the Employee
Try{
SessionFactory sf = Configuration.configure().buildSessionFactory(); Session session = sf.OpenSession(); Transaction tx = session.beginTransaction();
Employee emp = session.get(Employee.Class, new Long(1)); System.out.println(“Employee salary : ” + emp.getSalary()); Tx.commit(); }Catch(HibernateException e){ e.printStackTrace(); } CONFIDENTIAL
18
Features of Hibernate
Persistence for POJOs (JavaBeans) Flexible and intuitive mapping Support for fine-grained object models Powerful, high performance queries Dual-Layer Caching Architecture (HDLCA) Toolset for roundtrip development Support for detached objects (no DTOs) Automatic Dirty Checking Transitive Persistence Lazy Fetching Outer Join Fetching Runtime SQL Generation
CONFIDENTIAL
19
RDBMS Support
Hibernate is tested with wide range of databases.
DB2 7.1, 7.2; MySQL 3.23; PostgreSQL 7.1.2, 7.2, 7.3; Oracle 8i, 9i; Sybase 12.5 (JConnect 5.5); Interbase 6.0.1 (Open Source) With Firebird InterClient 2.01; HypersonicSQL 1.61, 1.7.0; Microsoft SQL Server 2000; Mckoi SQL 0.93 Progress 9 Pointbase Embedded 4.3 SAP DB 7.3 CONFIDENTIAL
20
Tools Support
XDoclet
Modeling tools / Code generator
Middlegen AndroMDA IDE Plug-in support: Eclipse, IDEA
CONFIDENTIAL
21
Hibernate References
Http://hibernate.org Hibernate in Action (Manning, 2004) Tool support
http://xdoclet.sf.net http://boss.bekk.no/boss/middlegen http://www.andromda.org/
CONFIDENTIAL
22
Important points to remember
Project uses RDBMS ? Need to have well-designed strategy to persistent objects.
The application performance considering data retrieval Simplicity in terms of coding
It maps the database tables same as their relations between each other – which we call domain models / POJO configuration file (hibernate.cfg.xml) mapping file and POJO Transaction, Connection Pooling, CRUD etc…
CONFIDENTIAL
23
Thank You
Mail:
[email protected]
CONFIDENTIAL
24