CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.

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

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.
Chapter 10: Designing Databases
Persistence Jim Briggs 1. 2 Database connectivity: JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets)
Fast Track to ColdFusion 9. Getting Started with ColdFusion Understanding Dynamic Web Pages ColdFusion Benchmark Introducing the ColdFusion Language Introducing.
Session-02.
Session-01. Hibernate Framework ? Why we use Hibernate ?
The Java Persistence API Edel Sherratt. Contents Revisit applications programming Using Java Persistence API.
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.
Java Persistence API Maciej Adamiak. Agenda -Entity, -Entity Operations, -Query Language.
Rice KRAD Data Layer JPA Design Eric Westfall July 2013.
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.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Maven for building Java applications By Nalin De Zoysa
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
IS-907 Java EE JPA: Simple Object-Relational Mapping.
© D. Wong  Indexes  JDBC  JDBC in J2EE (Java 2 Enterprise Edition)
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Object Oriented Analysis and Design 1 Chapter 7 Database Design  UML Specification for Data Modeling  The Relational Data Model and Object Model  Persistence.
Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.
EJB 3.0 Persistence Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.
Hibernate Persistence. What is Persistence Persist data to database or other storage.  In OO world, persistence means persist object to external storage.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
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.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
© D. Wong Security and User Authorization in SQL 8.7 pp. 410  Authorization ID = user name  Special authorization ID: PUBLIC  Privileges for:
The Java Persistence API ©SoftMoore ConsultingSlide 1.
Basics of JDBC Session 14.
Java Persistence API part 1 INFORMATICS ENGINEERING – UNIVERSITY OF BRAWIJAYA Eriq Muhammad Adams J
Java Persistence API (JPA) Relationships. Kinds of relationships UML associations and aggregations (ER non- identifying relationships, shared semantics)
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February
Database: SQL, MySQL, LINQ and Java DB © by Pearson Education, Inc. All Rights Reserved.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
IS-907 Java EE Introduction to JPA. Java Persistence API A framework for using relational databases in Java programs mapping between tables and classes,
1 10 Systems Analysis and Design in a Changing World, 2 nd Edition, Satzinger, Jackson, & Burd Chapter 10 Designing Databases.
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.
CS320 Web and Internet Programming SQL and MySQL Chengyu Sun California State University, Los Angeles.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
Hibernate Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan Java Annotation Lesson 1.
CS422 Principles of Database Systems Object-Oriented Features in DBMS Chengyu Sun California State University, Los Angeles.
1 Section 1 - Introduction to SQL u SQL is an abbreviation for Structured Query Language. u It is generally pronounced “Sequel” u SQL is a unified language.
XP Chapter 1 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Level 2 Objectives: Understanding and Creating Table.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.
Don't Know Jack About Object-Relational Mapping?
CS6320 – Java Persistence API
CS3220 Web and Internet Programming Database Access with JDBC
Chengyu Sun California State University, Los Angeles
CS320 Web and Internet Programming SQL and MySQL
Chengyu Sun California State University, Los Angeles
Advanced Java Programming
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
CS3220 Web and Internet Programming SQL and MySQL
Chengyu Sun California State University, Los Angeles
CS4961 Software Design Laboratory Understand Aquila Backend
CS3220 Web and Internet Programming SQL and MySQL
Chengyu Sun California State University, Los Angeles
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles

The Object-Oriented Paradigm The world consists of objects So we use object-oriented languages to write applications We want to store some of the application objects (a.k.a. persistent objects) So we use a Object Database?

The Reality of DBMS Relational DBMS are still predominant Best performance Most reliable Widest support Bridge between OO applications and relational databases CLI and embedded SQL Object-Relational Mapping (ORM) tools

Call-Level Interface (CLI) Application interacts with database through functions calls String sql = "select name from items where id = 1"; Connection c = DriverManager.getConnection( url ); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( sql ); if( rs.next() ) System.out.println( rs.getString(“name”) );

Embedded SQL SQL statements are embedded in host language String name; #sql {select name into :name from items where id = 1}; System.out.println( name );

Employee – Application Object public class Employee { Integerid; Stringname; Employeesupervisor; }

Employee – Database Table create table employees ( idinteger primary key, namevarchar(255), supervisor integer references employees(id) );

From Database to Application So how do we construct an Employee object based on the data from the database? public class Employee { Integerid; Stringname; Employeesupervisor; public Employee( Integer id ) { // access database to get name and supervisor … … }

Problems with CLI and Embedded SQL … SQL statements are hard-coded in applications public Employee( Integer id ) { … PreparedStatment p; p = connection.prepareStatment( “select * from employees where id = ?” ); … }

… Problems with CLI and Embedded SQL … Tedious translation between application objects and database tables public Employee( Integer id ) { … ResultSet rs = p.executeQuery(); if( rs.next() ) { name = rs.getString(“name”); … }

… Problems with CLI and Embedded SQL Application design has to work around the limitations of relational DBMS public Employee( Integer id ) { … ResultSet rs = p.executeQuery(); if( rs.next() ) { … supervisor = ?? }

The ORM Approach customer employee account Application Persistent Data Store ORM tool Oracle, MySQL, SQL Server … Flat files, XML …

Hibernate and JPA Java Persistence API (JPA) Annotations for object-relational mapping Data access API An object-oriented query language JPQL Hibernate The most popular Java ORM library An implementation of JPA

Hibernate Usage Hibernate without JPA API: SessionFactory, Session, Query, Transaction More features Hibernate with JPA API: EntityManagerFactory, EntityManager, Query, Transaction Better portability Behaviors are better defined and documented

A Hibernate Example Java classes Employee.java JPA configuration file persistence.xml Code to access the persistent objects EmployeeTest.java (Optional) Logging configuration files log4j.properties

Java Classes Plain Java classes (POJOs); however, it is recommended that Each persistent class has an identity field Each persistent class implements the Serializable interface Each persistent field has a pair of getter and setter, which don’t have to be public

O/R Mapping Annotations Describe how Java classes are mapped to relational Java (can be omitted)Fields of Fields of class types

persistence.xml name Database information Provider-specific properties No need to specify persistent classes

Access Persistent Objects EntityManagerFactory EntityManager Query and TypedQuery Transaction A transaction is required for updates

Some EntityManager Methods find( entityClass, primaryKey ) createQuery( query ) createQuery( query, resultClass ) persist( entity ) merge( entity ) getTransaction()

Persist() vs. Merge() ScenarioPersistMerge Object passed was never persisted 1. Object added to persistence context as new entity 2. New entity inserted into database at flush/commit 1. State copied to new entity. 2. New entity added to persistence context 3. New entity inserted into database at flush/commit 4. New entity returned Object was previously persisted, but not loaded in this persistence context 1. EntityExistsException thrown (or a PersistenceException at flush/commit) 1. Existing entity loaded. 2. State copied from object to loaded entity 3. Loaded entity updated in database at flush/commit 4. Loaded entity returned Object was previously persisted and already loaded in this persistence context 1. EntityExistsException thrown (or a PersistenceException at flush or commit time) 1. State from object copied to loaded entity 2. Loaded entity updated in database at flush/commit 3. Loaded entity returned

A Common Scenario That Needs Merge() 1. Load an object from database Open EntityManager Load object Close EntityManager 2. Save the object in HTTP session 3. Change some fields of the object 4. Save the object back to database Open EntityManager Save object Close EntityManager GET POST

The Returned Value of Merge() Employee e = new Employee(); e.setName( “Joe” ); entityManager.persist( e ); Employee e = new Employee(); e.setName( “Joe” ); entityManager.merge( e ); e.getId()  ??

Java Persistence Query Language (JPQL) A query language that looks like SQL, but for accessing objects Automatically translated to DB-specific SQL statements select e from Employee e where e.id = :id From all the Employee objects, find the one whose id matches the given value See Chapter 4 of Java Persistence API, Version 2.0

Hibernate Query Language (HQL) A superset of JPQL 2/manual/en-US/html/ch16.html

Join in HQL … class User { Integer id; String username; … } class Section { Integer id; User instructor; … } id userssections instructor_ididusername 1cysun 2vcrespi

… Join in HQL … Query: find all the sections taught by the user “cysun”. SQL?? HQL??

… Join in HQL … Database tables?? class User { Integer id; String username; … } class Section { Integer id; Set instructors; … }

… Join in HQL Query: find all the sections for which “cysun” is one of the instructors SQL?? HQL?? See SectionDaoImpl in CSNS2 for more HQL join examples

Advantages of ORM Make RDBMS look like ODBMS Data are accessed as objects, not rows and columns Simplify many common operations. E.g. e.getSupervisor().getName() Improve portability Use an object-oriented query language Separate DB specific SQL statements from application code Object caching

SchemaExport Part of the Hibernate Core library Generate DDL from Java classes and annotations In Hibernate Examples, run Hbm2ddl

Basic Object-Relational Mapping Class-level Id Fields of simple (can be omitted) Fields of class

Advanced ORM Embedded class Collections Inheritance

Embedded Class public class Address { String street; String city; String state; String zip; } users id…streetcitystatezip… public class User { Integer id; String username String password; Address address; }

Mapping Embedded public class Address { String street; String city; String state; String zip; public class User Integer id; String username String Address address; }

Collection of Simple Types public class Customer { Integer id; String name; String address; Set phones; }

Mapping Element Collection id customersCustomer_phones Set phones;

Customize name = “customer_phones”, = “customer_id”) Set phones;

List of Simple Types Order by ASC|DESC”) Simple types do not have properties Order by a = “phone_order”) List phones;

Issues Related to Collections of Object Types Relationships (a.k.a. associations) one-to-many many-to-many Unidirectional vs. Bidirectional Set and List Cascading behaviors

Types of Relationships Many-to-Many Many-to-One / One-to-Many One-to-One

Many-to-Many Relationship Each entity in E 1 can be related to many entities in E 2 Each entity in E 2 can be related to many entities in E 1 E1E1 E2E2

Many-to-One Relationship Each entity in E 1 can be related to one entities in E 2 Each entity in E 2 can be related to many entities in E 1 E1E1 E2E2

One-to-One Relationship Each entity in E 1 can be related to one entities in E 2 Each entity in E 2 can be related to one entities in E 1 E1E1 E2E2

Relationship Type Examples Books and authors?? Books and editors??

One-To-Many Example A customer may own multiple accounts An account only has one owner

Bidirectional Association – OO Design #1 public class Account { Integer id; Double balance; Date createdOn; Customer owner; } public class Customer { Integer id; String name; String address; Set phones; Set accounts; }

Unidirectional Association – OO Design #2 public class Account { Integer id; Double balance; Date createdOn; } public class Customer { Integer id; String name; String address; Set phones; Set accounts; }

Unidirectional Association – OO Design #3 public class Account { Integer id; Double balance; Date createdOn; Customer owner; } public class Customer { Integer id; String name; String address; Set phones; }

Unidirectional vs. Bidirectional Do the three OO designs result in different database schemas?? Does it make any difference on the application side?? Which one should we use??

Mapping Bidirectional One-To- Many public class Account { Integer id; Double balance; Date Customer owner; } public class Customer { Integer id; String name; String address; Set Set accounts; } property

Using List public class Customer { Integer id; String name; String address; “createdOn asc” ) List accounts; }

Many-To-Many Example A customer may own multiple accounts An account may have multiple owners

Mapping Many-To-Many public class Account { Integer id; Double balance; Date Set owners; } public class Customer { Integer id; String name; String address; Set Set accounts; } property

Customize name = “account_owners”, = “account_id”), ) Set owners;

Cascading Behavior Whether an operation on the parent object (e.g. Customer) should be applied to the children objects in a collection (e.g. List ) Customer c = new Customer(“cysun”); Account a1 = new Account(); Account a2 = new Account(); c.getAccounts().add( a1 ); c.getAccounts().add( a2 ); entityManager.persist(c); // will a1 and a2 be saved as well? entityManager.remove(c); // will a1 and a2 be deleted from db??

Cascading Types in JPA entation/jpa-2.0- api/javax/persistence/CascadeType.html

CascadeType cascade=CascadeType.PERSIST) List cascade={CascadeType.PERSIST, CascadeType.MERGE}) List cascade=CascadeType.ALL) List accounts;

Inheritance public class CDAccount extends Account { Integer term; }

Everything in One Table idaccount_typebalancecreated_onterm accounts Discriminator column

Inheritance Type @DiscriminatorValue(“CHECKING”) public class Account { public class CDAccount { … }

Table Per Subclass idbalancecreated_on accounts account_idterm cd_accounts foreign key

Inheritance Type @Inheritance(strategy=InheritanceType.JOINED) public class Account { public class CDAccount { … }

Table Per Concrete Class idbalancecreated_on accounts idbalancecreated_onterm cd_accounts

Inheritance Type @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public class Account { public class CDAccount { … }

Choosing Inheritance Types Consider the following queries List the information of all accounts (i.e. both checking and CD) List the information of CD accounts

Tips for Hibernate Mapping Understand relational design Know what the database schema should looks like before doing the mapping Understand OO design Make sure the application design is object- oriented

Further Readings TopLink JPA Annotation Reference – ddleware/ias/toplink-jpa-annotations html ddleware/ias/toplink-jpa-annotations html Pro JPA 2 by Mike Keith and Merrick Schincariol