hibernate basics
DESCRIPTION
Hibernate Basics. Basics. What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch. The Problem of Granularity. The Problem of Subtypes. The Problem of Identity. Problem relating to Association. The Problem of Object graph Navigation.. - PowerPoint PPT PresentationTRANSCRIPT
Hibernate Basics
Basics
What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.
The Problem of Granularity. The Problem of Subtypes. The Problem of Identity. Problem relating to Association. The Problem of Object graph Navigation.
User.java – name, userName, address, billingDetails etc BillingDetails .java – accountNumber, accountName,
accountType,user
The problem of Granularity
Problem of Subtype
SQL – no support for inheritance.
Polymorphic association Polymorphic query
Problem of Identity Object identity Object Equality Database identity UserName as key. Surrogate keys.
Problem relating to Associations Association in OO world – object reference Association in Relational Databases – foreign key Difference -Directional Example- User have Set of BillingDetails Example – In SQL by table joins and projection.
The problem of Object graph navigation- walking the object graph- Ex. user.getBillingDetails().getAccountNumber()- Relational database – join
Solutions of mismatch Paradigm:- Layered architecture- Hand coding a persistence layer with SQL/JDBC- Serialization- EJB- OO databases system – interact with database via intermediate SQL.
Other options : ORM- ORM - Advantages
-No SQL-Productivity-Maintainability- Performance- Vendor independent
“Hello World” with Hibernate
Message.java
package hello;public class Message {
private Long id;private String text;private Message nextMessage;
private Message() {}public Message(String text) {this.text = text;}// getter and setter
?xml version='1.0'encoding='utf-8'?><!DOCTYPE hibernate-configurationPUBLIC "-//Hibernate/Hibernate Configuration DTD//EN""http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"><hibernate-configuration><session-factory name="java:/hibernate/HibernateFactory"><property name="show_sql">true</property><property name="connection.datasource">java:/comp/env/jdbc/AuctionDB</property><property name="dialect">net.sf.hibernate.dialect.PostgreSQLDialect</property><property name="transaction.manager_lookup_class">net.sf.hibernate.transaction.JBossTransactionManagerLookup</property><mapping resource="auction/Item.hbm.xml"/></session-factory></hibernate-configuration>
Sample hibernate.cfg.xml configuration file
Hibernate mapping file.<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"><hibernate-mapping><classname="hello.Message"table="MESSAGES"><idname="id"column="MESSAGE_ID"><generator class="increment"/></id><propertyname="text"column="MESSAGE_TEXT"/><many-to-onename="nextMessage"cascade="all"column="NEXT_MESSAGE_ID"/></class></hibernate-mapping>
Session session = getSessionFactory().openSession();Transaction tx = session.beginTransaction();Message message = new Message("Hello World");session.save(message);tx.commit();session.close();
Generated SQL:
-insert into MESSAGES (MESSAGE_ID, MESSAGE_TEXT, NEXT_MESSAGE_ID)values (1, 'Hello World', null)
Saving a new message in database.
Updating a record
Session session = getSessionFactory().openSession();Transaction tx = session.beginTransaction();// 1 is the generated id of the first messageMessage message =(Message) session.load( Message.class, new Long(1) );message.setText("Greetings Earthling");Message nextMessage = new Message("Take me to your leader (please)");message.setNextMessage( nextMessage );tx.commit();session.close();
automatic dirty checkingcascade alltransactional write behind
This code calls three SQL statements inside the same transaction:
select m.MESSAGE_ID, m.MESSAGE_TEXT, m.NEXT_MESSAGE_IDfrom MESSAGES mwhere m.MESSAGE_ID = 1
insert into MESSAGES (MESSAGE_ID, MESSAGE_TEXT, NEXT_MESSAGE_ID)values (2, 'Take me to your leader (please)', null)
update MESSAGESset MESSAGE_TEXT = 'Greetings Earthling', NEXT_MESSAGE_ID = 2where MESSAGE_ID = 1
Core interfaces
Five core interfaces Session Interface
Primary, lightweight, not thread safe,cache or collection.
SessionFactory Interface Create sessions, single,shared by many application
thread. Configuration Interface
To configure and bootstrap the hibernate. Specify location of mapping files and create
sessionFactory.
Transaction interface Optional Abstract application code from underlying transaction
Query and Criteria interface Allow to perform queries Queries written in HQL or native SQL Bind query parameter, limit result and execute query Criteria interface similar to Query, allow to execute
OO criteria queries. Callback interface
Lifecycle and validate interface.
Implementing the domain model
Domain model should concern only with modeling of business domain.
Advantage – reuse, ease to unit test. Leakage of concerns - Transparent and Automated persistence Example - Message.java
HQL and Query by criteria (QBC) OO dialect of relation SQL language It is not DML HQL support – restriction,projection, order,
pagination,subqueries, aggregate function etc. Query by Criteria Example: Criteria object Criteria criteria = session.createCriteria(User.class);
criteria.add( Expression.like("firstname", "Max") );
List result = criteria.list(); Criterion object tree,less readable,validate at compile
time,extendable
Fetching Strategies
Different styles of fetching: Immediate fetching linked objects fetched immediate together with parent lazy fetching linked object fetched when link is navigated eager (outer join) fetching linked objects fetched immediate together with parent select-clause contains outer join-clause batch fetching not strictly a fetching strategy used to improve performance of lazy fetching
Different styles of fetching: Lazy Fetching = true<set name=”bids” lazy=”true” inverse=”true” >- n+1 trip to database
Batch fetching: <set name=”bids” lazy=”true” inverse=”true” batch-size=”10”> - n/10 + 1 trip to database - hibernate prefetch the next 10 collection when the first collection is accessed
Eager fetching <set name=”bids” lazy=”true” inverse=”true” outer-join=”true”>- not good, reduce concurrency- read lock- retrieving unnecessary data- solution : run time eager fetching mode
Fetching Strategies continue....
Hierarchy Mapping
Hierarchical relations between entities not supported in database
Three alternatives: Table per concrete class (concrete table inheritance)
table per class hierarchy (single table inheritance)
table per subclass (class table inheritance)
Table per subtype
create pk-fk relationships in database lots of joins to compose object SQL can not enforce consistency of model
Table per class hierarchy
used with few subclasses with few attributes gives a lot of null values in table violates normalisation rules easy refactoring discriminator
Table per concrete class No special mapping needed Create one mapping per class used when super class is abstract entity integrity can not be enforced by the database each change to super class -> change of all
subclass tables
Hierarchy mapping – general comments
You can not mix strategies within one hierarchyYou can mix strategies in your applicationChoose a hierarchy mapping strategy No polymorphic queries or associations needed table-per-class strategy Polymorphic queries or associations needed not to many subclasses and not to many attributes
in subclasses table-per-class-hierarchy many subclasses or many attributes in subclasses table-per-subclass