1 / 24

Hibernate Basics

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. .

twila
Download Presentation

Hibernate Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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. The problem of Granularity • User.java – name, userName, address, billingDetails etc • BillingDetails .java – accountNumber, accountName, accountType,user

  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 – joinSolutions 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. Sample hibernate.cfg.xml configuration file ?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"> <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>

  10. 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> <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="nextMessage" cascade="all" column="NEXT_MESSAGE_ID"/> </class> </hibernate-mapping>

  11. Saving a new message in database. 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)‏

  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. 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

  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

More Related