Java Persistence API Mario Peshev National Academy for Software Development academy.devbg.org Svetlin Nakov National Academy for Software Development academy.devbg.org.

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.
Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
Persistence Jim Briggs 1. 2 Database connectivity: JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets)
Entities and Persistence. Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational.
ORM Technologies and Entity Framework (EF)
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.
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.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
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.
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.
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.
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.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Efficient RDF Storage and Retrieval in Jena2 Written by: Kevin Wilkinson, Craig Sayers, Harumi Kuno, Dave Reynolds Presented by: Umer Fareed 파리드.
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 Nov 29, 2005 Object Relational Mapping Frameworks Wiene Höweler.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
The Java Persistence API ©SoftMoore ConsultingSlide 1.
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.
Introduction to Database Programming with Python Gary Stewart
OpenAccess ORM Advanced Topics Kevin Babcock April 9, 2009.
CompSci 280 S Introduction to Software Development
Introduction to Entity framework
Don't Know Jack About Object-Relational Mapping?
CS6320 – Java Persistence API
Chengyu Sun California State University, Los Angeles
Java Persistence Architecture (JPA)
Introduction to Entity Framework
Advanced Java Programming
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
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:

Java Persistence API Mario Peshev National Academy for Software Development academy.devbg.org Svetlin Nakov National Academy for Software Development academy.devbg.org

ContentsContents 1.About JPA 2.Entities 3.Queries 4.Mappings 5.Persistence 1.About JPA 2.Entities 3.Queries 4.Mappings 5.Persistence

About JPA Introduction

What is Java Persistence API (JPA)? Database persistence technology for Java Object-relational mapping (ORM) engine Operates with POJO entities Similar to Hibernate and JDO JPA maps Java classes to database tables Maps relationships between tables as associations between classes Provides CRUD functionality Create, read, update, delete What is Java Persistence API (JPA)? Database persistence technology for Java Object-relational mapping (ORM) engine Operates with POJO entities Similar to Hibernate and JDO JPA maps Java classes to database tables Maps relationships between tables as associations between classes Provides CRUD functionality Create, read, update, delete

History of JPA Created as part of EJB 3.0 within JSR 220 Released May 2006 as part of Java EE 5 Can be used as standalone library Standard API with many implementations OpenJPA – Hibernate – TopLink JPA – JPOX – History of JPA Created as part of EJB 3.0 within JSR 220 Released May 2006 as part of Java EE 5 Can be used as standalone library Standard API with many implementations OpenJPA – Hibernate – TopLink JPA – JPOX –

Part of “Glassfish” project on java.netPart of “Glassfish” project on java.net Glassfish is RI for the entire Java EE platformGlassfish is RI for the entire Java EE platform Sun and Oracle partnershipSun and Oracle partnership Sun Application Server + Oracle persistenceSun Application Server + Oracle persistence JPA open-source implementation called “TopLink Essentials”JPA open-source implementation called “TopLink Essentials” Donated by Oracle, derived from Oracle TopLinkDonated by Oracle, derived from Oracle TopLink All open source (under CDDL license)All open source (under CDDL license) Anyone can download/use source code or binary code in development or productionAnyone can download/use source code or binary code in development or production Part of “Glassfish” project on java.netPart of “Glassfish” project on java.net Glassfish is RI for the entire Java EE platformGlassfish is RI for the entire Java EE platform Sun and Oracle partnershipSun and Oracle partnership Sun Application Server + Oracle persistenceSun Application Server + Oracle persistence JPA open-source implementation called “TopLink Essentials”JPA open-source implementation called “TopLink Essentials” Donated by Oracle, derived from Oracle TopLinkDonated by Oracle, derived from Oracle TopLink All open source (under CDDL license)All open source (under CDDL license) Anyone can download/use source code or binary code in development or productionAnyone can download/use source code or binary code in development or production JPA Reference Implementation

EntitiesEntities Defining Simple Entity Classes

Just a POJO classJust a POJO class Abstract or concrete top level Java classAbstract or concrete top level Java class Non-final fields/properties, no-arguments constructorNon-final fields/properties, no-arguments constructor No required interfacesNo required interfaces No requirement for business or callback interfacesNo requirement for business or callback interfaces Direct field or property-based accessDirect field or property-based access Getter/setter can contain logic (e.g. validation)Getter/setter can contain logic (e.g. validation) Just a POJO classJust a POJO class Abstract or concrete top level Java classAbstract or concrete top level Java class Non-final fields/properties, no-arguments constructorNon-final fields/properties, no-arguments constructor No required interfacesNo required interfaces No requirement for business or callback interfacesNo requirement for business or callback interfaces Direct field or property-based accessDirect field or property-based access Getter/setter can contain logic (e.g. validation)Getter/setter can contain logic (e.g. validation) Anatomy of an Entity

Must be indicated as an annotation on the class: Entity entry in XML mapping file The Minimal public class Employee { … }

Must have a persistent identifier (primary key): The Minimal public class Employee int int id; public int getId() { return id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setId(int id) { this.id = id; }}

Identifier (id) in entity, primary key in databaseIdentifier (id) in entity, primary key in database Uniquely identifies entity in memory and in dbUniquely identifies entity in memory and in db Different ID definitionsDifferent ID definitions Simple idSimple id Compound idCompound id Embedded idEmbedded id Persistent Identity (Id)

Simple id – single field/property Compound id – multiple fields Embedded id – single field of PK class type Id int String EmployeePK id;

Identifiers can be generated in the databaseIdentifiers can be generated in the on the on the ID 3 pre-defined generation strategies:3 pre-defined generation strategies: IDENTITY, SEQUENCE, TABLEIDENTITY, SEQUENCE, TABLE May pre-exist or be generatedMay pre-exist or be generated AUTO strategy indicates that the provider will choose a strategyAUTO strategy indicates that the provider will choose a strategy int id; int id;

Using Identity or Sequence Using identity (auto increment column in the database) for Id generation:Using identity (auto increment column in the database) for Id generation: Using database sequence for Id generation:Using database sequence for Id generation: Using identity (auto increment column in the database) for Id generation:Using identity (auto increment column in the database) for Id generation: Using database sequence for Id generation:Using database sequence for private @SequenceGenerator(name="UsersSeq", sequenceName="USERS_SEQ") private long id; sequenceName="USERS_SEQ") private long id;

Mapping a property to a database column:Mapping a property to a database column: A column name can be explicitly given:A column name can be explicitly given: Simple Column public class Message { private String message; private String message; public void setMessage(String msg) { message = msg; } public void setMessage(String msg) { message = msg; } public String getMessage() { return message; } public String getMessage() { return message; private double salary;

Persistent Contexts and EntityManager Manipulating Database Entities

A set of “managed” entity instancesA set of “managed” entity instances Keyed by persistent identityKeyed by persistent identity Only one entity with a given persistent ID may exist in the PCOnly one entity with a given persistent ID may exist in the PC Added to the PC, but not individually removable (“detached”)Added to the PC, but not individually removable (“detached”) Managed by EntityManagerManaged by EntityManager Contents of PC change as a result of operations on EntityManager APIContents of PC change as a result of operations on EntityManager API Persistence Context (PC)

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

Entities Lifecycle

Client-visible object for operating on entitiesClient-visible object for operating on entities API for all the basic persistence operations (CRUD)API for all the basic persistence operations (CRUD) Manages connection and transactionManages connection and transaction Can think of it as a proxy to a persistence contextCan think of it as a proxy to a persistence context Entity Manager

EntityManager APIEntityManager API persist() – persists given entity object into the database (SQL INSERT)persist() – persists given entity object into the database (SQL INSERT) remove() – deletes given entity object into the database (SQL DELETE by PK)remove() – deletes given entity object into the database (SQL DELETE by PK) refresh() – reloads given entity object from the database (SQL SELECT by PK)refresh() – reloads given entity object from the database (SQL SELECT by PK) merge() – synchronize the state of detached entity with the PCmerge() – synchronize the state of detached entity with the PC find() – execute a simple query by PKfind() – execute a simple query by PK EntityManager APIEntityManager API persist() – persists given entity object into the database (SQL INSERT)persist() – persists given entity object into the database (SQL INSERT) remove() – deletes given entity object into the database (SQL DELETE by PK)remove() – deletes given entity object into the database (SQL DELETE by PK) refresh() – reloads given entity object from the database (SQL SELECT by PK)refresh() – reloads given entity object from the database (SQL SELECT by PK) merge() – synchronize the state of detached entity with the PCmerge() – synchronize the state of detached entity with the PC find() – execute a simple query by PKfind() – execute a simple query by PK Operations on Entities

createQuery() – creates a query instance using dynamic JPQLcreateQuery() – creates a query instance using dynamic JPQL createNamedQuery() – creates an instance for a predefined JPQL querycreateNamedQuery() – creates an instance for a predefined JPQL query createNativeQuery() – creates an instance for an SQL querycreateNativeQuery() – creates an instance for an SQL query contains() – determine if given entity is managed by the PCcontains() – determine if given entity is managed by the PC flush() – forces changes in the PC to be saved in the database (automatically called on transaction commit)flush() – forces changes in the PC to be saved in the database (automatically called on transaction commit) createQuery() – creates a query instance using dynamic JPQLcreateQuery() – creates a query instance using dynamic JPQL createNamedQuery() – creates an instance for a predefined JPQL querycreateNamedQuery() – creates an instance for a predefined JPQL query createNativeQuery() – creates an instance for an SQL querycreateNativeQuery() – creates an instance for an SQL query contains() – determine if given entity is managed by the PCcontains() – determine if given entity is managed by the PC flush() – forces changes in the PC to be saved in the database (automatically called on transaction commit)flush() – forces changes in the PC to be saved in the database (automatically called on transaction commit) Operations on Entities (2)

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

find()find() Obtain a managed entity instance (SQL SELECT by PK)Obtain a managed entity instance (SQL SELECT by PK) Return null if not foundReturn null if not found remove()remove() Delete a managed entity by PKDelete a managed entity by PK find() and remove() public void removeCustomer(Long custId) { Customer cust = entityManager. Customer cust = entityManager. find(Customer.class, custId); find(Customer.class, custId); entityManager.remove(cust); entityManager.remove(cust);}

Merges the state of detached entity into a managed copy of the detached entityMerges the state of detached entity into a managed copy of the detached entity Returned entity has a different Java identity than the detached entityReturned entity has a different Java identity than the detached entity May invoke SQL SELECTMay invoke SQL SELECT merge() public Customer storeUpdatedCustomer(Customer cust) { return entityManager.merge(cust); return entityManager.merge(cust);}

QueriesQueries Using JPQL

Dynamic or statically defined (named queries)Dynamic or statically defined (named queries) Criteria using JPQL (Java Persistence API Query Language, a kind of SQL)Criteria using JPQL (Java Persistence API Query Language, a kind of SQL) Native SQL support (when required)Native SQL support (when required) Named parameters bound at execution time (no SQL injection)Named parameters bound at execution time (no SQL injection) Queries

Pagination and ability to restrict size of resultPagination and ability to restrict size of result Single/multiple-entity results, data projectionsSingle/multiple-entity results, data projections Bulk update and delete operation on an entityBulk update and delete operation on an entity Standard hooks for vendor-specific hintsStandard hooks for vendor-specific hints Queries (2)

Query instances are obtained from factory methods on EntityManager, e.g.Query instances are obtained from factory methods on EntityManager, e.g. Query API:Query API: getResultList() – execute query returning multiple resultsgetResultList() – execute query returning multiple results getSingleResult() – execute query returning single resultgetSingleResult() – execute query returning single result executeUpdate() – execute bulk update or deleteexecuteUpdate() – execute bulk update or delete Query API Query query = entityManager.createQuery( "SELECT e from Employee e"); "SELECT e from Employee e");

setFirstResult() – set the first result to retrievesetFirstResult() – set the first result to retrieve setMaxResults() – set the maximum number of results to retrievesetMaxResults() – set the maximum number of results to retrieve setParameter() – bind a value to a named or positional parametersetParameter() – bind a value to a named or positional parameter setHint() – apply a vendor-specific hint to the querysetHint() – apply a vendor-specific hint to the query setFlushMode() – apply a flush mode to the query when it gets runsetFlushMode() – apply a flush mode to the query when it gets run Query API (2)

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

Return all instances of the given entity typeReturn all instances of the given entity type JPQL string composed from entity typeJPQL string composed from entity type For example, if “Account” was passed in then JPQL string would be: “select a from Account a”For example, if “Account” was passed in then JPQL string would be: “select a from Account a” Dynamic Queries – Example public List findAll(String entityName){ return entityManager.createQuery( return entityManager.createQuery( "select e from " + entityName + " e") "select e from " + entityName + " e").setMaxResults(100).setMaxResults(100).getResultList();.getResultList();}

Use createNamedQuery() factory method at runtime and pass in the query nameUse createNamedQuery() factory method at runtime and pass in the query name Query must be statically definedQuery must be statically defined Query names are “globally” scopedQuery names are “globally” scoped Provider can to precompile the queries and return errors at deployment timeProvider can to precompile the queries and return errors at deployment time Can include parameters and hints in static query definitionCan include parameters and hints in static query definition Named Queries

Named Queries – query="select s from Sale s where s.customer.id = :custId order by s.salesDate") public List findSalesByCustomer(Customer cust) { return (List )entityManager. return (List )entityManager. createNamedQuery("Sale.findByCustId") createNamedQuery("Sale.findByCustId").setParameter("custId", cust.getId()).setParameter("custId", cust.getId()).getResultList();.getResultList();}

ORM Mappings Annotations or XML

Map persistent object state to relational databaseMap persistent object state to relational database Map relationships to other entitiesMap relationships to other entities Metadata may be annotations or XML (or both)Metadata may be annotations or XML (or both) Object/Relational Mapping

Annotations Logical—object model model Physical—DB tables and columns tables and columns XMLXML Can specify scoped settings or defaultsCan specify scoped settings or defaults Standard rules for default db table/column namesStandard rules for default db table/column names Annotations / XML

State may be “fetched” as EAGER or LAZYState may be “fetched” as EAGER or LAZY LAZY – container defers loading until the field or property is accessedLAZY – container defers loading until the field or property is accessed EAGER – requires that the field or relationship be loaded when the referencing entity is loadedEAGER – requires that the field or relationship be loaded when the referencing entity is loaded Cascading of entity operations to related entitiesCascading of entity operations to related entities Setting may be defined per relationshipSetting may be defined per relationship Configurable globally in mapping file for persistence-by-reachabilityConfigurable globally in mapping file for persistence-by-reachability Fetching and Cascading

Direct mappings of fields to columnsDirect mappings of fields to – optional, indicates simple mapped – optional, indicates simple mapped attribute Can specify fetch=EAGER / LAZYCan specify fetch=EAGER / LAZY Maps any of the common simple Java typesMaps any of the common simple Java types Primitives, wrappers, serializable, etc.Primitives, wrappers, serializable, etc. Used in conjunction in conjunction Can override any of the defaultsCan override any of the defaults Simple Mappings

public class Customer { int id; String name; int c_rating; Image photo; } CUSTOMER “ CREDIT ” ) Simple Mappings

</entity>

Common relationship mappings supportedCommon relationship – – – collection Unidirectional or bidirectionalUnidirectional or bidirectional Owning and inverse sidesOwning and inverse sides Owning side specifies the physical mappingOwning side specifies the physical to specify foreign key to specify foreign key decouples physical relationship mappings from entity decouples physical relationship mappings from entity tables Relationship Mappings

public class Sale { int id;... Customer cust; } SALE CUST_ID @Id... ManyToOne Mapping

</entity>

public class Sale { int id;... Customer cust; } public class Customer { int id;... Set sales; } CUSTOMER ID... “ cust ” ) OneToMany Mapping

</entity>

Using Persistence API Creating JPA Applications

Persistence in Java SE No deployment phaseNo deployment phase Application must use a “Bootstrap API” to obtain an EntityManagerFactoryApplication must use a “Bootstrap API” to obtain an EntityManagerFactory Resource-local EntityManagersResource-local EntityManagers Application uses a local EntityTransaction obtained from the EntityManagerApplication uses a local EntityTransaction obtained from the EntityManager

Entity Transactions Only used by resource-local EntityManagersOnly used by resource-local EntityManagers Transaction demarcation under explicit application control using EntityTransaction APITransaction demarcation under explicit application control using EntityTransaction API begin(), commit(), rollback(), isActive()begin(), commit(), rollback(), isActive() Underlying (JDBC) resources allocated by EntityManager as requiredUnderlying (JDBC) resources allocated by EntityManager as required

Persistence Class javax.persistence.Persistencejavax.persistence.Persistence Root class for bootstrapping an EntityManagerRoot class for bootstrapping an EntityManager Locates provider service for a named persistence unitLocates provider service for a named persistence unit Invokes on the provider to obtain an EntityManagerFactoryInvokes on the provider to obtain an EntityManagerFactory

EntityManagerFactory Class javax.persistence.EntityManagerFactoryjavax.persistence.EntityManagerFactory Obtained by the PersistanceObtained by the Persistance Creates EntityManager for a named persistence unit or configurationCreates EntityManager for a named persistence unit or configuration In Java SE environment the persistence unit configuration is defined in the META-INF/persistence.xml fileIn Java SE environment the persistence unit configuration is defined in the META-INF/persistence.xml file

Sample Configuration ( META- INF/persistence.xml ) <persistence xmlns=" xmlns:xsi=" version="1.0"> xmlns:xsi=" version="1.0"> hellojpa.Message hellojpa.Message <property name="openjpa.ConnectionURL" <property name="openjpa.ConnectionURL" value="jdbc:derby:openjpa-database;create=true"/> value="jdbc:derby:openjpa-database;create=true"/> <property name="openjpa.ConnectionDriverName" <property name="openjpa.ConnectionDriverName" value="org.apache.derby.jdbc.EmbeddedDriver"/> value="org.apache.derby.jdbc.EmbeddedDriver"/> </persistence>

OpenJPA Enhancer OpenJPA uses class files enhancerOpenJPA uses class files enhancer Enhancements are critical for the normal work of the OpenJPA!Enhancements are critical for the normal work of the OpenJPA! Provide optimal runtime performance, flexible lazy loading, and efficient, immediate dirty trackingProvide optimal runtime performance, flexible lazy loading, and efficient, immediate dirty tracking Enhancement can be done at build time, during the deployment or at runtimeEnhancement can be done at build time, during the deployment or at runtime To switch on runtime class enhancement use the following VM parameters:To switch on runtime class enhancement use the following VM parameters: OpenJPA uses class files enhancerOpenJPA uses class files enhancer Enhancements are critical for the normal work of the OpenJPA!Enhancements are critical for the normal work of the OpenJPA! Provide optimal runtime performance, flexible lazy loading, and efficient, immediate dirty trackingProvide optimal runtime performance, flexible lazy loading, and efficient, immediate dirty tracking Enhancement can be done at build time, during the deployment or at runtimeEnhancement can be done at build time, during the deployment or at runtime To switch on runtime class enhancement use the following VM parameters:To switch on runtime class enhancement use the following VM parameters: -javaagent:lib/openjpa jar

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

Java Persistence API Live Demo

IDE Support Eclipse “Dali” project ( )Eclipse “Dali” project ( ) JPA supportJPA support NetBeans ( )NetBeans ( ) EJB 3.0 support including JPA (Beta 2)EJB 3.0 support including JPA (Beta 2) JDeveloper ( )JDeveloper ( ) EJB 3.0 support including JPA ( )EJB 3.0 support including JPA ( )

SummarySummary JPA emerged from best practices of existing best of breed ORM productsJPA emerged from best practices of existing best of breed ORM products Lightweight persistent POJOs, no extra baggageLightweight persistent POJOs, no extra baggage Simple, compact and powerful APISimple, compact and powerful API Standardized object-relational mapping metadata specified using annotations or XMLStandardized object-relational mapping metadata specified using annotations or XML Feature-rich query languageFeature-rich query language Java EE integration, additional API for Java SEJava EE integration, additional API for Java SE JPA emerged from best practices of existing best of breed ORM productsJPA emerged from best practices of existing best of breed ORM products Lightweight persistent POJOs, no extra baggageLightweight persistent POJOs, no extra baggage Simple, compact and powerful APISimple, compact and powerful API Standardized object-relational mapping metadata specified using annotations or XMLStandardized object-relational mapping metadata specified using annotations or XML Feature-rich query languageFeature-rich query language Java EE integration, additional API for Java SEJava EE integration, additional API for Java SE

Java Persistence API Questions?Questions?

ExercisesExercises 1.Define an entity class Student which has Id, FirstName and LastName. 2.Define an entity class Course which has Id, name and list of students. 3.Create a database matching the entity classes. Use Apache Derby and its built-in identity columns support. 4.Create a program that lists all classes and the students in each class. 5.Create a program that adds a new class and few students inside it. 1.Define an entity class Student which has Id, FirstName and LastName. 2.Define an entity class Course which has Id, name and list of students. 3.Create a database matching the entity classes. Use Apache Derby and its built-in identity columns support. 4.Create a program that lists all classes and the students in each class. 5.Create a program that adds a new class and few students inside it.

ExercisesExercises