Download presentation
Presentation is loading. Please wait.
Published byAnnis Long Modified over 9 years ago
1
Hibernate Basics
2
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.
3
User.java – name, userName, address, billingDetails etc BillingDetails.java – accountNumber, accountName, accountType,user The problem of Granularity
4
Problem of Subtype SQL – no support for inheritance. Polymorphic association Polymorphic query
5
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.
6
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.
7
Other options : ORM - ORM - Advantages -No SQL -Productivity -Maintainability - Performance - Vendor independent
8
“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
9
?xml version='1.0'encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate- configuration-2.0.dtd"> true java:/comp/env/jdbc/AuctionDB net.sf.hibernate.dialect.PostgreSQLDialect net.sf.hibernate.transaction.JBossTransactio nManagerLookup Sample hibernate.cfg.xml configuration file
10
Hibernate mapping file. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> <class name="hello.Message" table="MESSAGES"> <id name="id" column="MESSAGE_ID"> <property name="text" column="MESSAGE_TEXT"/> <many-to-one name="nextMessage" cascade="all" column="NEXT_MESSAGE_ID"/>
11
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.
12
Updating a record Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); // 1 is the generated id of the first message Message 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 checking cascade all transactional write behind
13
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
14
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.
15
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.
16
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
17
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
18
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
19
Different styles of fetching: Lazy Fetching = true - n+1 trip to database Batch fetching: - n/10 + 1 trip to database - hibernate prefetch the next 10 collection when the first collection is accessed Eager fetching - not good, reduce concurrency- read lock - retrieving unnecessary data - solution : run time eager fetching mode Fetching Strategies continue....
20
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)
21
Table per subtype create pk-fk relationships in database lots of joins to compose object SQL can not enforce consistency of model
22
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
23
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
24
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.