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

Slides:



Advertisements
Similar presentations
TPTP Data Model 1 Database support for TPTP EMF based data models using Elver/Hibernate Guru Nagarajan July 14, 2006.
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.
Persistence Jim Briggs 1. 2 Database connectivity: JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets)
EmbeddedSQL: 1 Impedance Mismatch Problem Problem : How to connect SQL statements with conventional programming languages Different models of language.
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.
Introduction to JPA Java Persistence API Introduction to JPA.
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.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
Database System Concepts and Architecture Lecture # 3 22 June 2012 National University of Computer and Emerging Sciences.
Database Programming in Java Corresponds with Chapter 32, 33.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
Entity Beans BMP Celsina Bignoli
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.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.
© 2011 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 14 Using Relational Databases to Provide Object Persistence (Overview) Modern Database.
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.
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.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
JPA / HIBERNATE CSCI 6370 Nilayan Bhattacharya Sanket Sable.
Topic : Hibernate 3:Advanced ORM Kaster Nurmukan.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Basics of JDBC Session 14.
Java Persistence API part 1 INFORMATICS ENGINEERING – UNIVERSITY OF BRAWIJAYA Eriq Muhammad Adams J
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
© 1997 UW CSE 10/27/97H-1 Embedded SQL and the CLI Chapter 7.7.
IS-907 Java EE Introduction to JPA. Java Persistence API A framework for using relational databases in Java programs mapping between tables and classes,
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
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.
JAVA Persistence API(JPA) What is it? How would we use it in a project? Should we use it? -Parag Chaudhari.
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.
CS520 Web Programming Full Text Search 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.
Introduction to Database Programming with Python Gary Stewart
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
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?
CS3220 Web and Internet Programming Database Access with JDBC
Chengyu Sun California State University, Los Angeles
CS320 Web and Internet Programming SQL and MySQL
A very brief introduction
CS520 Web Programming Spring – Inversion of Control
Advanced Java Programming
CS5220 Advanced Topics in Web Programming Spring – Web MVC
Hibernate Bayu Priyambadha, S.Kom.
CS5220 Advanced Topics in Web Programming Spring – Web MVC
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 (I) 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 ( id integer primary key, name varchar(255), supervisor_id 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 PostgreSQL, MySQL, Oracle, SQL Server …

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 class Employee.java Code to access the database EmployeeTest.java JPA configuration file persistence.xml (Optional) Logging configuration file log4j.properties

Persistent Class A class whose objects need to be saved (i.e. persisted) in a database Any Java model class can be a persistent class, though 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 doGet() doPost()

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 … class User { Integer id; String username; … } class Section { Integer id; Set instructors; … } id userssections idusername 1cysun 2vcrespi instructors instructor_idsection_id

… 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

Benefits of ORM Remove the mismatch between OO design in application and relational design in database Simplify data access Data is accessed as objects, i.e. no manual conversion between objects and rows/columns necessary JPQL/HQL queries are usually simpler than SQL queries Often times queries are automatically generated by the ORM tool, e.g. e.getSupervisor().getSupervisor().getname() Improve DBMS independency Object caching