Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.

Slides:



Advertisements
Similar presentations
V 6, Mats Strandberg ORM With Hibernate.
Advertisements

Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
An Object/Relational Mapping tool Free and open source Simplifies storage of object data in a relational database Removes the need to write and maintain.
Persistence Jim Briggs 1. 2 Database connectivity: JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets)
NHibernate Object/Relational Persistence for.NET.
Hibernate 1. Introduction ORM goal: Take advantage of the things SQL databases do well, without leaving the Java language of objects and classes. ORM.
Fast Track to ColdFusion 9. Getting Started with ColdFusion Understanding Dynamic Web Pages ColdFusion Benchmark Introducing the ColdFusion Language Introducing.
Database Management: Getting Data Together Chapter 14.
Fundamentals, Design, and Implementation, 9/e Chapter 11 Managing Databases with SQL Server 2000.
Object Relational Mapping. What does ORM do? Maps Object Model to Relational Model. Resolve impedance mismatch. Resolve mapping of scalar and non-scalar.
Data Management Design
Chapter 11 Data Management Layer Design
ORM Object-Relational Mapping 1. Object Persistence Persistence is the ability of an object to survive the lifecycle of the process, in which it resides.
Session-02.
Session-01. Hibernate Framework ? Why we use Hibernate ?
An Introduction to Hibernate Matt Secoske
Data Persistence and Object-Relational Mapping Slides by James Brucker, used with his permission 1.
Chapter One Overview of Database Objectives: -Introduction -DBMS architecture -Definitions -Data models -DB lifecycle.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Data Access Patterns. Motivation Most software systems require persistent data (i.e. data that persists between program executions). In general, distributing.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Enterprise Object Framework. What is EOF? Enterprise Objects Framework is a set of tools and resources that help you create applications that work with.
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
DBMS Lecture 9  Object Database Management Group –12 Rules for an OODBMS –Components of the ODMG standard  OODBMS Object Model Schema  OO Data Model.
Data Access Patterns Some of the problems with data access from OO programs: 1.Data source and OO program use different data modelling concepts 2.Decoupling.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
Database Technical Session By: Prof. Adarsh Patel.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
Seminar on. Overview Hibernate. What is it? Hibernate. How does it work? Hibernate Tools.
Object/Relational Mapping with Hibernate Practical ORM.
CS 157B: Database Management Systems II February 6 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
Object Oriented Analysis and Design 1 Chapter 7 Database Design  UML Specification for Data Modeling  The Relational Data Model and Object Model  Persistence.
1 Part 2: EJB Persistency Jianguo Lu. 2 Object Persistency A persistent object is one that can automatically store and retrieve itself in permanent storage.
© 2011 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 14 Using Relational Databases to Provide Object Persistence (Overview) Modern Database.
Hibernate Persistence. What is Persistence Persist data to database or other storage.  In OO world, persistence means persist object to external storage.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
1 Mapping to Relational Databases Presented by Ramona Su.
Hibernate Introduction - 1 Present by Eric Yu. BeanSoft | 2 Content Understanding object/relational persistence Introduction Architecture The core interfaces.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005.
An Introduction to Object/Relational Persistence and Hibernate Yi Li
Oct * Brad Tutterow. VS 2008.NET 3.5LINQ Entity Framework  The ADO.NET Entity Framework is part of Microsoft’s next generation of.NET technologies.
A U.S. Department of Energy Office of Science Laboratory Operated by The University of Chicago Argonne National Laboratory Office of Science U.S. Department.
JPA / HIBERNATE CSCI 6370 Nilayan Bhattacharya Sanket Sable.
Intoduction to NHibernate. Agenda Overview of NHibernate Models and Mappings Configuration Sessions and Transactions Queries.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Session 1 Module 1: Introduction to Data Integrity
Persistence – Iteration 4 Vancouver Bootcamp Aaron Zeckoski
Object storage and object interoperability
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Introduction – ORM, Helloworld Application
Chapter 3: Relational Databases
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
Sean Chambers.  ORM stands for Object Relational Mapper  Maps your POCO (plain old clr objects) to your relational model using XML config  Relieves.
Hibernate Basics 廖峻鋒 Sep 14,2004 NTU Dept. of CSIE.
CS422 Principles of Database Systems Object-Relational Mapping (ORM) Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Hibernate Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
HIBERNATE/Java Overview of technology for Hibernate by محمد حسن کاظمی پوران Master : M.M.Nematollahi.
OpenAccess ORM Advanced Topics Kevin Babcock April 9, 2009.
Don't Know Jack About Object-Relational Mapping?
Chengyu Sun California State University, Los Angeles
Object-Oriented Database Management System (ODBMS)
Object/Relational Mapping with Hibernate
Java Data Persistence Using Hibernate
Hibernate Bayu Priyambadha, S.Kom.
Data Model.
Presentation transcript:

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-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" " 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

Hibernate mapping file. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" " <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"/>

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

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  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 - n+1 trip to database Batch fetching: - n/ 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....

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