Topic : Hibernate 2: Object Persistence and ORM Kaster Nurmukan.

Slides:



Advertisements
Similar presentations
Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
Advertisements

Copyright ©2010 Oracle Corporation Made available under Creative Commons Attribution-Share Alike 3.0 Unported EclipseLink Runtime Architecture Data Source.
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.
Bruce Scharlau, University of Aberdeen, 2012 Data storage options for mobiles Mobile Computing.
Chapter 10: Designing Databases
Raptor Technical Details. Outline Workshop structured by Raptor workflow – Raptor Event model. – ICA log file parsing – ICA/MUA event storage – ICA event.
Persistence Jim Briggs 1. 2 Database connectivity: JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets)
Spring, Hibernate and Web Services 13 th September 2014.
.NET Database Technologies: Open-Source Frameworks.
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.
ORM Technologies and Entity Framework (EF)
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.
Data Access Patterns. Motivation Most software systems require persistent data (i.e. data that persists between program executions). In general, distributing.
Object Persistence and Object-Relational Mapping James Brucker.
Introduction to JPA Java Persistence API Introduction to JPA.
Hibernatification! Roadmap for Migrating from Plain Old SQL on JDBC to JPA on Hibernate Duke Banerjee Senior Developer, DrillingInfo.com.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Training - Day 3 OJB. What is OR Mapping? OR Mapping is the mapping of relational database tables to objects (Java Objects in our case) Many OR Mapping.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Neo.NET Entity Objects Design Goals Copyright © Erik Dörnenburg – Last updated: May 2004.
UPortal Developers MIT August 2004 Persistence Strategy for uPortal 3 Mike DeSimone the r-smart group
Agenda What is Hibernate Spring Integration Questions Overview
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
Entity Beans BMP Celsina Bignoli
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
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.
Chapter 14 - Designing Data Access Classes1 Chapter 14 Designing Data Access Classes.
© 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.
JBoss at Work Databases and JBoss Chapter 4 Jeff Schmitt October 26, 2006.
Chapter 8 Databases.
Domain and Persistence Patterns. Fundamental Pattern Types Design Patterns Business Logic Patterns.
(1) Introduction to Models using the Play Framework Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University.
DAY 14: MICROSOFT ACCESS – CHAPTER 1 Madhuri Siddula October 1, 2015.
MCS 270 Spring 2014 Object-Oriented Software Development.
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.
Middleware Technology (J2EE/EJB) Entity Bean (JBoss EJB 3.0 tutorial)
Topic : Hibernate 3:Advanced ORM Kaster Nurmukan.
Fall CIS 764 Database Systems Engineering L18.2 : Object Relational Mapping … ….Object persistence.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
1 Nov 29, 2005 Object Relational Mapping Frameworks Wiene Höweler.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
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
SQL and Java The vision for Java is to be the concrete and nails that people use to build this incredible network system that is happening all around us.
Fundamentals of MyBATIS
Introduction to ORM Hibernate Hibernate vs JDBC. May 12, 2011 INTRODUCTION TO ORM ORM is a programming technique for converting data between relational.
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
Google Code Libraries Dima Ionut Daniel. Contents What is Google Code? LDAPBeans Object-ldap-mapping Ldap-ODM Bug4j jOOR Rapa jongo Conclusion Bibliography.
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 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.
Fall CIS 764 Database Systems Engineering L11: Object Relational Mapping … (a) ORM, Object persistence (b) Pets sequence.
HIBERNATE/Java Overview of technology for Hibernate by محمد حسن کاظمی پوران Master : M.M.Nematollahi.
Chengyu Sun California State University, Los Angeles
Object Relational DBMSs
A very brief introduction
POOL persistency framework for LHC
Intro to Relational Databases
Testing a persistence layer
Developing and testing enterprise Java applications
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Topic : Hibernate 2: Object Persistence and ORM Kaster Nurmukan

Overview of table relashionship with Object

Applications need to save data to persistent storage. Persistent storage can be database, directory service, XML files, spreadsheet,... For O-O programming, we'd like to save and retrieve objects to/from storage. Java Application object Persistent Storage

Object-Relational Paradigm Mismatch  Database stores data as rows in tables, which are not like objects.  Objects have associations and collections databases have relations between tables.  Objects are unique, database row data is copied each time you query it.

Purpose save object as a row in a database table create object using data from table save and create associations between objects Design Goals separate O-R mapping service from our application localize the impact of change in database

An Event Manager application with these classes:

Map between an object and a row in a database table. LOCATIONS PKidINTEGER nameVARCHAR(80) addressVARCHAR(160) Location id: int name: String address: String Class should have an identifier attribute Database Table identifier is usually the primary key of table Object Mapper convert object to table row data, convert data types, instantiates objects

LOCATIONS idnameaddress 101Kasetsart University90 Pahonyotin Seacon Square120 Srinakarin... ku : Location id = 101 name = "Kasetsart University" address = "90 Pahonyotin..." object diagram save( )

Location ku = new Location( "Kasetsart University" ); ku.setAddress( "90 Pahonyotin Road; Bangkok" ); // save the location objectMapper.save( ku ); Issues: mapper should choose a unique ID for saved objects what happens if same data is already in the table?

// retrieve the location Location ku1 = objectMapper.find ("Kasetsart University"); Location ku2 = objectMapper.find ("Kasetsart University");  what field does find( ) search for? id field? name field?  does mapper always return the same object? ( ku1 == ku2 ) => true or false?

// retrieve the location Location ku1 = objectMapper.find( 111 ); List ku_list = objectMapper.query( "'SELECT WHERE name LIKE 'Kasetsart U%'"); Provide two kinds of "find". find( key ) - find object by primary key query( string ) - find objects using a flexible query language. May return many matches.

Location ku = new Location( "Kasetsart University" ); ku.setAddress( "90 Pahonyotin Road; Bangkok" ); // save the location objectMapper.save( ku ); // change the address ku.setAddress( "Kampaengsaen, Nakorn Pathom" ); With transparent persistence, changes to a "managed" object are automatically propagated to the database. LOCATIONS idnameaddress 101Kasetsart UniversityKampaengsaen Seacon Square120 Srinakarin...

Event id: int name: String startDate: Date location: Location Location id: int name: String address: String 1 *

Event id: int name: String startDate: Date location: Location LOCATIONS PKidINTEGER nameVARCHAR addressVARCHAR Location id: int name: String address: String EVENTS PKidINTEGER nameVARCHAR start_date TIMESTAMP FKlocation_id INTEGER The ORM converts a n-to-1 association to a foreign key relation (persist) or foreign key to object (retrieve). 1 *

Event event = new Event( "Java Days" ); Location ku = new Location( "Kasetsart University" ); ku.setAddress( "90 Pahonyotin Road; Bangkok" ); event.setLocation( ku ); event.setStartDate( new Date(108,Calendar.JULY, 1) ); // save the event objectMapper.save( event ); When we save the event, does it save the location, too? Is this done automatically? Save an Event...

// delete the event Event evt = objectMapper.find( "Java Days" ); objectMapper.delete( evt ); Does the dataMapper delete the Location, too? What if other Events (in database) still refer to this Location?

// retrieve the event Event evt = objectMapper.find( "Java Days" ); Location location = evt.getLocation( ); // null? When we get the event, does the ORM fetch the location, too?

Event id: int name: String startDate: Date Speaker id: int name: String telephone: String speakers *

Event id: int name: String startDate: Date SPEAKERS PKidINTEGER nameVARCHAR telephoneVARCHAR FKevent_idINTEGER Speaker id: int name: String telephone: String EVENTS PKidINTEGER nameVARCHAR start_date TIMESTAMP FKlocation_id INT Event has a collection of Speakers. The ORM saves a collection as Speaker entries with FK reference to Event. speakers *

Event event = new Event( "Java Days" ); event.setLocation( ku ); // add event speakers Speaker gosling = new Speaker( "James Gosling" ); Speaker yuen = new Speaker( "Prof. Yuen" ); event.getSpeakers().add( gosling ); event.getSpeakers().add( yuen ); // save the event objectMapper.save( event ); Issues: same issues as many-to-1 association

// retrieve the event Event evt = objectMapper.find("Java Days"); Collection speakers = evt.getSpeakers( ); What kind of collection does ORM return? Can we use any collection we want? List? ArrayList?

Event id: int name: String startDate: Date Speaker id: int name: String telephone: String speakers {ordered}*

Event id: int name: String startDate: Date SPEAKERS PKidINTEGER nameVARCHAR FKevent_idINTEGER speaker_idxINT Speaker id: int name: String EVENTS PKidINTEGER nameVARCHAR start_date TIMESTAMP FKlocation_id INT Event has a list or array of Speakers. The ORM must store a foreign key and a list index in the Speaker table. sessions {ordered}*

Event id: int name: String startDate: Date Attendee id: int name: String telephone: String attendees * events *

Event id: int name: String startDate: Date ATTENDEES PKidINTEGER nameVARCHAR telephoneVARCHAR Attendee id: int name: String telephone: String EVENTS PKidINTEGER nameVARCHAR start_date TIMESTAMP FKlocation_id INT attendees * events * EVENT_ATTENDEE PKidINTEGER FKevent_idINTEGER FKattendee_idINTEGER

Event id: int name: String startDate: Date Attendee id: int name: String telephone: String Registration confirmed: boolean pricePaid: Money Sometimes the association has modeling significance. An Attendee has a collection of Registrations.

When you save/update/delete an object in database... are associated objects also saved/updated/deleted? e: Event Attendee attendees {set} EVENTS table ATTENDEES table save( e ) ?

In JPA, using class Event cascade=PERSIST) private List attendees; NONE PERSIST REFRESH REMOVE ALL

In Hibernate mapping file for Event: cascade= "none"don't cascade operations "all"cascade all operations (be careful) "save-update"cascade save and updates "delete-orphan"cascade all, delete unreferenced orphan children

When you create an object from database... when are associated objects created? e: Event Attendee attendees {set} EVENTS table ATTENDEE table find( id ) ?

Example: get a Country from Country database. Country china = orm.query( "SELECT c FROM Country c WHERE c.name='China'"); System.out.println( "Population is "+china.getPopulation() ); Country cities: Set City has 363 cities How many objects are created? a) One - just the Country object b) Country + all 363 cities

Eager: create all associated object immediately. Lazy: create associated objects only when they are referenced. Country china = orm.query("SELECT c FROM..."); System.out.println( "Population is "+china.getPopulation() ); for(City c: china.getCities() ) Sytem.out.println("has city: "+city); EAGER LAZY

The query or connection object might be closed before the code accesses the cities. // This code uses JPA em = entityManagerFactory.getEntityManager(); Query q = em.createQuery("SELECT c FROM..."); Country china = q.getSingleResult(); // close entity manager to free resources em.close( ); for(City c: china.getCities() ) Sytem.out.println("has city: "+city); ERROR: not attached to database

Common O-R operations are: Create - save (persist) a new object in the database Retrieve an object from the database Update data for an object already saved in database Delete object data from the database

Object Mapper find( id ) : T query( query : String ): T[*] findAll( ) : T[*] save( object : T ) update( object : T ) delete( object : T ) T A UML Type Parameter The method to "find" an Object by its identifier maybe named: load( id ) the Hibernate and Spring name find( id, Class )JPA get( id ) similar to load but no exception if id is not found

This class is generally called a Data Access Object (DAO). Hibernate uses the term "data access object". Append "Dao" to the class name, e.g. EventDao. EventDao find( id: int ) : Event query( query: String ) : Event[*] save( evt: Event ) update( evt: Event ) delete( evt: Event )

User Interface Application Logic Domain Objects DAO O-R Mapping Framework Other Services JDBC Foundation Classes ui event CRUD request ORM API domain object data xfer object JDBC API ResultSet, etc.

In some applications, Object-Relational mapping is inefficient. Example: display a table of attendees NameTelephone Bill B. PersonDao TableModel RowSet Person objects

1. No ORM -- JDBC in my code. No Layers! Put the JDBC right in your app code. 2. Do It Myself. Write your own DAO using JDBC. 3. Use a Framework. Hibernate, MyBatis, TopLink, or other. 4. Use a Standard. Java Persistence Architecture (JPA) or Java Data Objects (JDO) provide a standard API that have many implementations.

If you want to... do It yourself Study path:  SQL Fundamentals  JDBC Fundamentals  Design and Code use a framework  How to use Hibernate  Configure a Database use a stardard  How to use JPA  Configure a Database

Hibernate - most popular open-source persistence framework for Java. NHibernate for.Net. Uses POJOs and object-query language. Completely decouple Java from database. Can reverse engineer. MyBatis - simple, uses SQL maps. Database schema not transparent to Java code. Cayenne - Apache project, has GUI modeler that eliminates need to write xml. Can reverse engineer database or generate database schema & Java code. TopLink (Oracle) Torque (Apache DB) Castor,...

Java Persistence API (JPA) standard for persistence of plain java objects. Can be used with stand-alone or enterprise apps. Good IDE support. –EclipseLink, TopLink Essentials (Glassfish project), OpenJPA. DataNucleus, Hibernate Annotations. Java Data Objects (JDO) transparent persistence of POJOs; can persist to LDAP, RDBMS, Excel, and other –Kodo, DataNucleus

Article: Adopting a Java Persistence Framework, persistence-framework.html

Web4J ( web + database in Java without O-R mapping. Interesting & educational web site Presents arguments why not to use a framework (but doesn't mention Hibernate).