Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Java Persistence API Mario Peshev National Academy for Software Development academy.devbg.org Svetlin Nakov National Academy for Software Development academy.devbg.org."— Presentation transcript:

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

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

3 About JPA Introduction

4 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

5 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 – http://openjpa.apache.org/http://openjpa.apache.org/ Hibernate – http://www.hibernate.orghttp://www.hibernate.org TopLink JPA – http://www.oracle.com/technology/jpa http://www.oracle.com/technology/jpa JPOX – http://www.jpox.org/http://www.jpox.org/ 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 – http://openjpa.apache.org/http://openjpa.apache.org/ Hibernate – http://www.hibernate.orghttp://www.hibernate.org TopLink JPA – http://www.oracle.com/technology/jpa http://www.oracle.com/technology/jpa JPOX – http://www.jpox.org/http://www.jpox.org/

6 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

7 EntitiesEntities Defining Simple Entity Classes

8 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

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

10 Must have a persistent identifier (primary key): The Minimal Entity @Entity public class Employee { @Id int id; @Id 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; }}

11 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)

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

13 Identifiers can be generated in the databaseIdentifiers can be generated in the database @GeneratedValue on the ID@GeneratedValue 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 Identifier Generation @Id @GeneratedValue @Id @GeneratedValue int id; int id;

14 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 Id generation: @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Id @GeneratedValue(generator="UsersSeq") @SequenceGenerator(name="UsersSeq", sequenceName="USERS_SEQ") private long id; sequenceName="USERS_SEQ") private long id;

15 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 Mappings @Entity 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; }} @Column(name="SAL") private double salary;

16 Persistent Contexts and EntityManager Manipulating Database Entities

17 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)

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

19 Entities Lifecycle

20 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

21 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

22 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)

23 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;}

24 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);}

25 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);}

26 QueriesQueries Using JPQL

27 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

28 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)

29 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");

30 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)

31 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

32 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();}

33 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

34 Named Queries – Example @NamedQuery(name="Sale.findByCustId", 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();}

35 ORM Mappings Annotations or XML

36 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

37 Annotations Logical—object model (e.g. @OneToMany)Logical—object model (e.g. @OneToMany) Physical—DB tables and columns (e.g. @Table)Physical—DB tables and columns (e.g. @Table) 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

38 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

39 Direct mappings of fields to columnsDirect mappings of fields to columns @Basic – optional, indicates simple mapped attribute@Basic – 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 with @ColumnUsed in conjunction with @Column Can override any of the defaultsCan override any of the defaults Simple Mappings

40 public class Customer { int id; String name; int c_rating; Image photo; } CUSTOMER IDNAMECREDIT PHOTO @Entity @Id @Lob @Column(name= “ CREDIT ” ) Simple Mappings

41 </entity>

42 Common relationship mappings supportedCommon relationship mappings supported @ManyToOne, @OneToOne – single entity@ManyToOne, @OneToOne – single entity @OneToMany, @ManyToMany – collection@OneToMany, @ManyToMany – collection Unidirectional or bidirectionalUnidirectional or bidirectional Owning and inverse sidesOwning and inverse sides Owning side specifies the physical mappingOwning side specifies the physical mapping @JoinColumn to specify foreign key column@JoinColumn to specify foreign key column @JoinTable decouples physical relationship mappings from entity tables@JoinTable decouples physical relationship mappings from entity tables Relationship Mappings

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

44 ...... </entity>

45 public class Sale { int id;... Customer cust; } public class Customer { int id;... Set sales; } CUSTOMER ID... SALE CUST_IDID... @Entity @ManyToOne @Id @Entity @Id @OneToMany(mappedBy= “ cust ” ) OneToMany Mapping

46 ...... </entity>

47 Using Persistence API Creating JPA Applications

48 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

49 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

50 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

51 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

52 Sample Configuration ( META- INF/persistence.xml ) <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0"> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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>

53 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-1.0.2.jar

54 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(); }}

55 Java Persistence API Live Demo

56 IDE Support Eclipse “Dali” project ( http://www.eclipse.org/dali )Eclipse “Dali” project ( http://www.eclipse.org/dali ) http://www.eclipse.org/dali JPA supportJPA support NetBeans ( http://community.java.net/netbeans )NetBeans ( http://community.java.net/netbeans ) http://community.java.net/netbeans EJB 3.0 support including JPA (Beta 2)EJB 3.0 support including JPA (Beta 2) JDeveloper ( http://otn.oracle.com/jdev )JDeveloper ( http://otn.oracle.com/jdev ) http://otn.oracle.com/jdev EJB 3.0 support including JPA (10.1.3.1)EJB 3.0 support including JPA (10.1.3.1)

57 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

58 Java Persistence API Questions?Questions?

59 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.

60 ExercisesExercises


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

Similar presentations


Ads by Google