Hibernate Basics Basics What is persistence Persistence in

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.

The problem of Granularity User. java – name, user. Name, address, billing. Details etc Billing. Details. java – account. Number, account. Name, account. Type, user

Problem of Subtype SQL – no support for inheritance. Polymorphic association Polymorphic query

Problem of Identity Object identity Object Equality Database identity User. Name 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 Billing. Details Example – In SQL by table joins and projection.

The problem of Object graph navigation - walking the object graph - Ex. user. get. Billing. Details(). get. Account. Number() - 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 - 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 next. Message; private Message() {} public Message(String text) { this. text = text; } // getter and setter

Sample hibernate. cfg. xml configuration file ? xml version='1. 0'encoding='utf-8'? > <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate Configuration DTD//EN" "http: //hibernate. sourceforge. net/hibernate -configuration-2. 0. dtd"> <hibernate-configuration> <session-factory name="java: /hibernate/Hibernate. Factory"> <property name="show_sql">true</property> <property name="connection. datasource"> java: /comp/env/jdbc/Auction. DB </property> <property name="dialect"> net. sf. hibernate. dialect. Postgre. SQLDialect </property> <property name="transaction. manager_lookup_class"> net. sf. hibernate. transaction. JBoss. Transacti on. Manager. Lookup </property> <mapping resource="auction/Item. hbm. xml"/> </session-factory> </hibernate-configuration>

Hibernate mapping file. <? xml version="1. 0"? > <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate Mapping DTD//EN" "http: //hibernate. sourceforge. net/hibernate-mapping-2. 0. dtd"> <hibernate-mapping> <class name="hello. Message" table="MESSAGES"> <id name="id" column="MESSAGE_ID"> <generator class="increment"/> </id> <property name="text" column="MESSAGE_TEXT"/> <many-to-one name="next. Message" cascade="all" column="NEXT_MESSAGE_ID"/> </class> </hibernate-mapping>

Saving a new message in database. Session session = get. Session. Factory(). open. Session(); Transaction tx = session. begin. Transaction(); 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)

Updating a record Session session = get. Session. Factory(). open. Session(); Transaction tx = session. begin. Transaction(); // 1 is the generated id of the first message Message message = (Message) session. load( Message. class, new Long(1) ); message. set. Text("Greetings Earthling"); Message next. Message = new Message("Take me to your leader (please)"); message. set. Next. Message( next. Message ); tx. commit(); session. close(); automatic dirty checking cascade all transactional write behind

This code calls three SQL statements inside the same transaction: select m. MESSAGE_ID, m. MESSAGE_TEXT, m. NEXT_MESSAGE_ID from MESSAGES m where m. MESSAGE_ID = 1 insert into MESSAGES (MESSAGE_ID, MESSAGE_TEXT, NEXT_MESSAGE_ID) values (2, 'Take me to your leader (please)', null) update MESSAGES set MESSAGE_TEXT = 'Greetings Earthling', NEXT_MESSAGE_ID = 2 where MESSAGE_ID = 1

Core interfaces Five core interfaces Session Interface Session. Factory Interface Primary, lightweight, not thread safe, cache or collection. Create sessions, single, shared by many application thread. Configuration Interface To configure and bootstrap the hibernate. Specify location of mapping files and create session. Factory.

Transaction interface Query and Criteria interface Optional Abstract application code from underlying transaction 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. create. Criteria(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

Fetching Strategies continue. . 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

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 hierarchy You can mix strategies in your application Choose 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
- Slides: 24