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
![Page 1: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/1.jpg)
Hibernate Basics
![Page 2: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/2.jpg)
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.
![Page 3: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/3.jpg)
User.java – name, userName, address, billingDetails etc BillingDetails .java – accountNumber, accountName,
accountType,user
The problem of Granularity
![Page 4: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/4.jpg)
Problem of Subtype
SQL – no support for inheritance.
Polymorphic association Polymorphic query
![Page 5: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/5.jpg)
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.
![Page 6: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/6.jpg)
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.
![Page 7: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/7.jpg)
Other options : ORM- ORM - Advantages
-No SQL-Productivity-Maintainability- Performance- Vendor independent
![Page 8: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/8.jpg)
“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
![Page 9: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/9.jpg)
?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
![Page 10: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/10.jpg)
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>
![Page 11: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/11.jpg)
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.
![Page 12: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/12.jpg)
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
![Page 13: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/13.jpg)
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
![Page 14: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/14.jpg)
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.
![Page 15: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/15.jpg)
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.
![Page 16: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/16.jpg)
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
![Page 17: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/17.jpg)
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
![Page 18: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/18.jpg)
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
![Page 19: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/19.jpg)
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....
![Page 20: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/20.jpg)
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)
![Page 21: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/21.jpg)
Table per subtype
create pk-fk relationships in database lots of joins to compose object SQL can not enforce consistency of model
![Page 22: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/22.jpg)
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
![Page 23: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/23.jpg)
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
![Page 24: Hibernate Basics](https://reader036.vdocuments.site/reader036/viewer/2022070404/56813c90550346895da63b59/html5/thumbnails/24.jpg)
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