The Java Persistence API ©SoftMoore ConsultingSlide 1.

Slides:



Advertisements
Similar presentations
Copyright ©2010 Oracle Corporation Made available under Creative Commons Attribution-Share Alike 3.0 Unported EclipseLink Runtime Architecture Data Source.
Advertisements

15 Copyright © 2005, Oracle. All rights reserved. Container-Managed Relationships (CMRs)
Persistence Jim Briggs 1. 2 Database connectivity: JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets)
JBoss Seam: Contextual Components Jason Bechtel
Entities and Persistence. Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational.
Advanced Java programming (Java EE)
Session-02.
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.
Object Persistence and Object-Relational Mapping James Brucker.
Introduction to JPA Java Persistence API Introduction to JPA.
JPQL Java Persistence Query Language. Introduction The Java Persistence API specifies a query language that allows to define queries over entities and.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
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.
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.
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
1 Lecture 17 George Koutsogiannakis/SUMMER 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
Java Persistence API Mario Peshev National Academy for Software Development academy.devbg.org Svetlin Nakov National Academy for Software Development academy.devbg.org.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
Entity Beans BMP Celsina Bignoli
1 Java Persistence API JPA. 2 Agenda Motivation JPA Entities EntityManager & the Persistent Context Persistence Units Exceptions JPA Query Language.
IS-907 Java EE JPA: Simple Object-Relational Mapping.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
Container-Managed Persistence (CMP) Entity Beans Lesson 3A / Slide 1 of 42J2EE Server Components Objectives In this lesson, you will learn to: Identify.
Hitachi Consulting IOUG Collaborate ‘08 EJB 3.0 Java Persistence API (JPA) with Oracle TopLink Bill Lyons Systems Architect Hitachi Consulting
Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.
Enterprise Java Java Persistence: EntityManager. Enterprise Java v070903Java Persistence: EntityManager2 Goals Become familiar with the Java Persistence.
1 Mapping Persistent Objects Entities represent data in the database, so changes to an entity bean result in changes to the database. That's ultimately.
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.
1 Architectural Overview For application developers, assembling enterprise beans requires little or no expertise in the complex system-level issues that.
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.
Topic : Hibernate 2: Object Persistence and ORM Kaster Nurmukan.
1 Persistence in Java Enterprise Container Managed Persistence Application Managed Persistence Michael Brockway Sajjad Shami CG0165: Advanced Applications.
Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005.
MCS 270 Spring 2014 Object-Oriented Software Development.
Middleware Technology (J2EE/EJB) Entity Bean (JBoss EJB 3.0 tutorial)
Topic : Hibernate 3:Advanced ORM Kaster Nurmukan.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
1 Persistence: EntityManager In Java EE 5, persistence has been spun off into its own specification: Java Persistence 1.0. Persistence provides an ease-of-use.
Faculty of Information Technology Advanced Java programming (J2EE) Java Persistence API Based on the JPA presentation from javabeat.net.
Java Persistence API part 1 INFORMATICS ENGINEERING – UNIVERSITY OF BRAWIJAYA Eriq Muhammad Adams J
v110912Java Persistence: EntityManager2 Overview Earlier versions of EJB Specification defined the persistence layer –javax.ejb.EntityBean Java EE 5 moved.
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
JPA The New Enterprise Persistence Standard Mike Keith
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,
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
1 Entity Callbacks and Listeners When you execute EntityManager methods like persist( ), merge( ), remove( ), and find( ), or when you execute EJB QL queries,
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.
Object-Relational Mapping. Contents  Default Mapping Rules  Elementary Mapping  Embeddables  Relationship Mapping  Inheritance Mapping.
Don't Know Jack About Object-Relational Mapping?
CS6320 – Java Persistence API
Chengyu Sun California State University, Los Angeles
Java Persistence Architecture (JPA)
Advanced Java Programming
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
JPA: Mapping to an existing database
Developing and testing enterprise Java applications
Topics Persistence API for JAVA EE5 Java Transaction API Entity class.
Chengyu Sun California State University, Los Angeles
Presentation transcript:

The Java Persistence API ©SoftMoore ConsultingSlide 1

The Java Persistence API The Java Persistence API (JPA) is a Java programming language framework that allows developers to manage relational data in Java development environments. Provides a higher-level framework than JDBC for managing persistent objects Background –originated within the Enterprise JavaBeans 3.0 (JSR 220) expert group, but a Java EE application server is not required –merged expertise from TopLink, Hibernate, JDO, EJB vendors, and individuals –first released in May 2006 as part of Java EE 5 ©SoftMoore ConsultingSlide 2

JPA Implementations GlassFish (Java EE application server) –reference implementation –called “TopLink Essentials” (derived from Oracle TopLink) – Eclipse Persistence Services Project (EclipseLink) JBoss Hibernate Apache OpenJPA ©SoftMoore ConsultingSlide 3

JPA Major Components The API –defined in the javax.persistence package The Java Persistence Query Language (JPQL) –used to make queries against entities stored in a relational database –resembles SQL but operates against entity objects rather than database tables Object/Relational Metadata –can be specified directly in the entity class using annotations or in a separate XML descriptor file ©SoftMoore ConsultingSlide 4

JPA Overview JPA provides persistence for “Plain Old Java Object” (POJO) entities. Entities can be defined using annotations or an XML mapping file. An entity typically represents a table in a relational database, and each object of the class corresponds to a row in that table. Primary keys and relationships are also indicated by appropriate annotations on the entity class or entries in the XML mapping file. Entities are managed by an entity manager. ©SoftMoore ConsultingSlide 5

Requirements for Entity Classes Must be annotated with javax.persistence.Entity Must have a public or protected, no-argument constructor (may have other constructors) Must not be declared final. Also, no methods or persistent instance variables must be declared final. Must have persistent instance variables declared as private, protected, or package-private –entity’s state accessed through accessor (get) methods May need to implement the Serializable interface (if passed by value in a remote call) ©SoftMoore ConsultingSlide 6

Persistent Fields and Properties The persistent state of an entity can be accessed either through the entity’s instance variables or through JavaBeans-style properties. –If the mapping annotations are applied to the entity’s instance variables, the entity uses persistent fields. –If the mapping annotations are applied to the entity’s getter methods for JavaBeans-style properties, the entity uses persistent properties. You cannot apply mapping annotations to both fields and properties in a single entity. ©SoftMoore ConsultingSlide 7

Java Types for Persistent Fields/Properties Primitive types String Enumerated types Other entities and/or collections of entities –java.util.Collection –java.util.Set –java.util.List –java.util.Map Embeddable classes Other serializable types: –Wrappers classes –java.math.BigInteger –java.math.BigDecimal –java.util.Date –java.util.Calendar –java.sql.Date –java.sql.Time –java.sql.TimeStamp –User-defined serializable types –byte[] –Byte[] –char[] –Character[] ©SoftMoore ConsultingSlide 8

The Minimal Entity Must be annotated as an Entity Must have a persistent identifier (primary key) Example using public class Employee private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } } ©SoftMoore ConsultingSlide 9

The Minimal Entity (continued) Example Entity entry in XML mapping file ©SoftMoore ConsultingSlide 10

Identifier in entity, primary key in database Uniquely identifies entity in memory and in database Examples –Simple id – single int id; –Compound id – multiple int String name; –Embedded id – single field of PK class EmployeePK id; Uses PK class Persistent Identity

Identifiers can be generated in the database by on the identifier Three pre-defined generation strategies: –IDENTITY –SEQUENCE –TABLE Specifying strategy of AUTO indicates that the provider will choose int id; Identifier Generation

Persistence Context Abstraction representing a set of “managed” entity instances –Entities keyed by their persistent identity –Only one entity with a given persistent identity may exist in the persistence context –Entities are added to the persistence context, but are not individually removable (“detached”) Controlled and managed by EntityManager –Contents of persistent context change as a result of operations on EntityManager API

Application Persistence Context Entities MyEntity A MyEntity B MyEntity C MyEntity a EntityManager MyEntity b Entity state Persistence Context

Entity Manager Client-visible artifact for operating on entities –API for all the basic persistence operations Can think of it as a proxy to a persistence context –May access multiple different persistence contexts throughout its lifetime Multi-dimensionality leads to different aspects of EntityManager (and persistence context) naming –Transaction type, life cycle

EntityManager Methods persist() - insert the entity into the database remove() - delete the entity from the database refresh() - reload the entity state from the database merge() - synchronize state of detached entity with the persistence context find() - execute a simple primary key query createQuery() - create query instance using dynamic JPQL createNamedQuery() - create instance for a predefined query createNativeQuery() - create instance for an SQL query contains() - true if entity is managed by persistence context flush() - force synchronization of persistence context to database

Method persist() Insert a new entity instance into the database Save the persistent state of the entity and any owned relationship references Entity instance becomes managed Example public Customer createCustomer(int id, String name) { Customer cust = new Customer(id, name); entityManager.persist(cust); return cust; }

Method find() Obtains a managed entity instance with a given persistent identity –returns null if not found Example public void removeCustomer(Long custId) { Customer cust = entityManager.find(Customer.class, custId); entityManager.remove(cust); }

Queries Dynamic or statically defined (named queries) Criteria using JPQL Native SQL support when required Named parameters bound at execution time Pagination and ability to restrict size of result Single/multiple-entity results Bulk update and delete operation on an entity Standard hooks for vendor-specific hints

Queries Query instances are obtained from factory methods on EntityManager Query methods –getResultList() - execute query returning multiple results –getSingleResult() - execute query returning single result –executeUpdate() - execute bulk update or delete –setFirstResult() - set the first result to retrieve –setMaxResults() - set the maximum number of results to retrieve –setHint() - apply a vendor-specific hint to the query –setFlushMode() - apply a flush mode to the query when it gets run

Dynamic Queries Use createQuery() factory method at runtime and pass in the JPQL query string Use correct execution method –getResultList() –getSingleResult() –executeUpdate() Query may be compiled/checked at creation time or when executed Maximal flexibility for query definition and execution

Example: Dynamic Queries public List findAll(String entityName) { return entityManager.createQuery( "select e from " + entityName + " e").setMaxResults(100).getResultList(); }

Named Queries Use createNamedQuery() factory method at runtime and pass in the query name Query must have already been statically defined either in an annotation or XML Query names are “globally” scoped Provider has opportunity to precompile the queries and return errors at deployment time Can include parameters and hints in static query definition

Example: Named query="select s from Sale s where s.customer.id = :custId order by s.salesDate") /** * Returns all sales for a given customer */ public List findSalesByCustomer(Customer cust) { return entityManager.createNamedQuery("Sale.findByCustId").setParameter("custId", cust.getId()).getResultList(); }

Object/Relational Mapping Map persistent object state to relational database Map relationships to other entities Metadata may be annotations or XML (or both) Annotations –Logical: object model ) –Physical: database tables and columns ) XML can additionally specify scoped settings or defaults Standard rules for default database table/column names

Object/Relational Mapping (continued) State or relationships may be loaded or “fetched” as EAGER or LAZY –LAZY - hint to defer loading until the field or property is accessed –EAGER - requires that the field or relationship be loaded when the referencing entity is loaded Cascading of entity operations to related entities –Setting may be defined per relationship –Configurable globally in mapping file for persistence-by-reachability

Simple Mappings Direct mappings of fields/properties to columns Maps any of the common simple Java types –primitives– wrappers –enumerated– serializable –etc. Used in conjunction Defaults to the type deemed most appropriate if no mapping annotation is present Can override any of the defaults

CUSTOMER IDNAMECREDIT PHOTO Simple public class Customer private int id; private String private int private Image photo; }

Relationship Mappings Common relationship mappings (single (collection of entities) Unidirectional or bidirectional Owning and inverse sides of every bidirectional relationship Owning side specifies the physical mapping to specify foreign key column decouples physical relationship mappings from entity tables

CUSTOMER...ID SALE CUST_ID ID... Many-to-One public class Sale private int private Customer cust; }

CUSTOMER ID... SALE CUST_IDID... OneToMany public class Customer private int private Set sales; public class Sale private int private Customer cust; }

Persistence in Java SE No deployment phase –Application must use a “Bootstrap API” to obtain an EntityManagerFactory Application uses a local EntityTransaction obtained from the EntityManager –begin()– commit() –rollback()– isActive() New application-managed persistence context for every EntityManager –No propagation of persistence contexts

Bootstrap Classes javax.persistence.Persistence –root class for bootstrapping an EntityManager –used to obtain an EntityManagerFactory javax.persistence.EntityManagerFactory –creates EntityManager objects for a named persistence unit or configuration

Example public class PersistenceProgram { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("SomePUnit"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); // Perform finds, execute queries, // update entities, etc. em.getTransaction().commit(); em.close(); emf.close(); }

References The Java EE Tutorial, Part VIII: Persistence. Pro EJB 3: Java Persistence API by Mike Keith and Merrick Schincariol, Apress, 2006, ISBN: ©SoftMoore ConsultingSlide 35