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

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

Embed Size (px)

Citation preview

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

Java Persistence APIJava Persistence API

Mario PeshevMario PeshevNational Academy for Software National Academy for Software DevelopmentDevelopment

academy.devbg.org

Svetlin NakovSvetlin NakovNational Academy for Software National Academy for Software

DevelopmentDevelopment

academy.devbg.org

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

ContentsContentsContentsContents

1.1. About JPAAbout JPA

2.2. EntitiesEntities

3.3. QueriesQueries

4.4. MappingsMappings

5.5. PersistencePersistence

1.1. About JPAAbout JPA

2.2. EntitiesEntities

3.3. QueriesQueries

4.4. MappingsMappings

5.5. PersistencePersistence

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

About JPAAbout JPAIntroductionIntroduction

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

About JPAAbout JPAAbout JPAAbout JPA

• 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

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

History of JPAHistory of JPAHistory of JPAHistory of JPA

• 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/

• Hibernate – http://www.hibernate.org

• TopLink JPA – http://www.oracle.com/technology/jpa

• JPOX – 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/

• Hibernate – http://www.hibernate.org

• TopLink JPA – http://www.oracle.com/technology/jpa

• JPOX – http://www.jpox.org/

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

• Part of Part of ““GlassfishGlassfish”” project on java.net 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 persistence Sun Application Server + Oracle persistence

• JPA open-source implementation JPA open-source implementation called called ““TopLink EssentialsTopLink Essentials””• Donated by Oracle, derived from Oracle Donated by Oracle, derived from Oracle

TopLinkTopLink

• All open source (under CDDL license)All open source (under CDDL license)• Anyone can download/use source code or Anyone can download/use source code or

binary code in development or productionbinary code in development or production

• Part of Part of ““GlassfishGlassfish”” project on java.net 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 persistence Sun Application Server + Oracle persistence

• JPA open-source implementation JPA open-source implementation called called ““TopLink EssentialsTopLink Essentials””• Donated by Oracle, derived from Oracle Donated by Oracle, derived from Oracle

TopLinkTopLink

• All open source (under CDDL license)All open source (under CDDL license)• Anyone can download/use source code or Anyone can download/use source code or

binary code in development or productionbinary code in development or production

JPA Reference JPA Reference ImplementationImplementation

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

EntitiesEntitiesDefining Simple Entity ClassesDefining Simple Entity Classes

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

• Just a POJO classJust a POJO class

• Abstract or concrete top level Java class Abstract or concrete top level Java class

• Non-final fields/properties, no-arguments Non-final fields/properties, no-arguments constructorconstructor

• No required interfacesNo required interfaces

• No requirement for business or callback No requirement for business or callback interfacesinterfaces

• Direct field or property-based accessDirect field or property-based access

• Getter/setter can contain logic (e.g. Getter/setter can contain logic (e.g. validation)validation)

• Just a POJO classJust a POJO class

• Abstract or concrete top level Java class Abstract or concrete top level Java class

• Non-final fields/properties, no-arguments Non-final fields/properties, no-arguments constructorconstructor

• No required interfacesNo required interfaces

• No requirement for business or callback No requirement for business or callback interfacesinterfaces

• Direct field or property-based accessDirect field or property-based access

• Getter/setter can contain logic (e.g. Getter/setter can contain logic (e.g. validation)validation)

Anatomy of an EntityAnatomy of an Entity

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

• Must be indicated as an Entity

• @Entity annotation on the class:

• Entity entry in XML mapping file

The Minimal EntityThe Minimal Entity

@Entity@Entitypublic class Employee { … }public class Employee { … }

<entity class="com.acme.Employee"/><entity class="com.acme.Employee"/>

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

• Must have a persistent identifier (primary key):

The Minimal EntityThe Minimal Entity

@Entity@Entitypublic class Employee {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; }}}}

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

• Identifier (id) in entity, primary key in Identifier (id) in entity, primary key in databasedatabase

• Uniquely identifies entity in memory Uniquely identifies entity in memory and in dband in db

• Different ID definitionsDifferent ID definitions

• Simple idSimple id

• Compound idCompound id

• Embedded idEmbedded id

Persistent Identity (Id)Persistent Identity (Id)

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

• Simple id – single field/property

• Compound id – multiple fields

• Embedded id – single field of PK class type

Id DefinitionsId Definitions

@Id int id;@Id int id;

@Id int id;@Id int id;@Id String name;@Id String name;

@EmbeddedId EmployeePK id;@EmbeddedId EmployeePK id;

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

• Identifiers can be generated in the databaseIdentifiers can be generated in the database

• @@GeneratedValueGeneratedValue on the ID on the ID

• 3 pre-defined generation strategies:3 pre-defined generation strategies:

• IDENTITY, SEQUENCE, TABLE IDENTITY, SEQUENCE, TABLE

• May pre-exist or be generatedMay pre-exist or be generated

• AUTO strategy indicates that the provider will AUTO strategy indicates that the provider will choose a strategychoose a strategy

Identifier GenerationIdentifier Generation

@Id @GeneratedValue @Id @GeneratedValue int id;int id;

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

Using Identity or SequenceUsing Identity or SequenceUsing Identity or SequenceUsing Identity or Sequence

• Using identity (auto increment column in Using identity (auto increment column in the database) for Id generation:the database) for Id generation:

• Using database sequence for Id generation:Using database sequence for Id generation:

• Using identity (auto increment column in Using identity (auto increment column in the database) for Id generation:the database) for Id generation:

• Using database sequence for Id generation:Using database sequence for Id generation:

@Id@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@GeneratedValue(strategy=GenerationType.IDENTITY)private int id; private int id;

@Id@Id@GeneratedValue(generator="UsersSeq")@GeneratedValue(generator="UsersSeq")@SequenceGenerator(name="UsersSeq",@SequenceGenerator(name="UsersSeq", sequenceName="USERS_SEQ")sequenceName="USERS_SEQ")private long id;private long id;

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

• Mapping a property to a database Mapping a property to a database column:column:

• A column name can be explicitly given:A column name can be explicitly given:

Simple Column MappingsSimple Column Mappings

@Entity@Entitypublic class Message {public class Message { private String message;private String message; public void setMessage(String msg) {public void setMessage(String msg) { message = msg; }message = msg; } public String getMessage() { return message; }public String getMessage() { return message; }}}

@Column(name="SAL")@Column(name="SAL")private double salary;private double salary;

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

Persistent Contexts Persistent Contexts and and EntityManagerEntityManager

Manipulating Database EntitiesManipulating Database Entities

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

• A set of A set of “managed”“managed” entity instances entity instances • Keyed by persistent identityKeyed by persistent identity

• Only one entity with a given persistent ID Only one entity with a given persistent ID may exist in the PCmay exist in the PC

• Added to the PC, but not individually Added to the PC, but not individually removable (removable (“detached”“detached”))

• Managed by Managed by EntityManagerEntityManager

• Contents of PC change as a result of Contents of PC change as a result of operations on operations on EntityManagerEntityManager API API

Persistence Context (PC)Persistence Context (PC)

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

Application Persistence Context

Entities

MyEntity A

MyEntity B

MyEntity C

MyEntity a

EntityManager

MyEntity b

Entity state

Persistence Context (PC)Persistence Context (PC)

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

Entities LifecycleEntities LifecycleEntities LifecycleEntities Lifecycle

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

• Client-visible object for operating on Client-visible object for operating on entitiesentities

• API for all the basic persistence API for all the basic persistence operations (CRUD)operations (CRUD)

• Manages connection and transactionManages connection and transaction

• Can think of it as a proxy to a Can think of it as a proxy to a persistence contextpersistence context

Entity ManagerEntity Manager

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

• EntityManager APIEntityManager API

• persist() persist() – persists given entity object into – persists given entity object into the database (SQL INSERT)the database (SQL INSERT)

• remove() remove() – – deletesdeletes given entity object into given entity object into the database (SQL DELETE by PK)the database (SQL DELETE by PK)

• refresh() refresh() – reloads given entity object from – reloads given entity object from the database (SQL SELECT by PK)the database (SQL SELECT by PK)

• merge() merge() – synchronize the state of detached – synchronize the state of detached entity with the PCentity with the PC

• find() find() – execute a simple query by PK– execute a simple query by PK

• EntityManager APIEntityManager API

• persist() persist() – persists given entity object into – persists given entity object into the database (SQL INSERT)the database (SQL INSERT)

• remove() remove() – – deletesdeletes given entity object into given entity object into the database (SQL DELETE by PK)the database (SQL DELETE by PK)

• refresh() refresh() – reloads given entity object from – reloads given entity object from the database (SQL SELECT by PK)the database (SQL SELECT by PK)

• merge() merge() – synchronize the state of detached – synchronize the state of detached entity with the PCentity with the PC

• find() find() – execute a simple query by PK– execute a simple query by PK

Operations on EntitiesOperations on Entities

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

• createQuery()createQuery() – creates a query instance – creates a query instance using dynamic JPQLusing dynamic JPQL

• createNamedQuery()createNamedQuery() – creates an instance – creates an instance for a predefined JPQL queryfor a predefined JPQL query

• createNativeQuery()createNativeQuery() – creates an instance – creates an instance for an SQL queryfor an SQL query

• contains()contains() – determine if given entity is – determine if given entity is managed by the PCmanaged by the PC

• flush()flush() – forces changes in the PC to be – forces changes in the PC to be saved in the database (automatically called saved in the database (automatically called on transaction commit)on transaction commit)

• createQuery()createQuery() – creates a query instance – creates a query instance using dynamic JPQLusing dynamic JPQL

• createNamedQuery()createNamedQuery() – creates an instance – creates an instance for a predefined JPQL queryfor a predefined JPQL query

• createNativeQuery()createNativeQuery() – creates an instance – creates an instance for an SQL queryfor an SQL query

• contains()contains() – determine if given entity is – determine if given entity is managed by the PCmanaged by the PC

• flush()flush() – forces changes in the PC to be – forces changes in the PC to be saved in the database (automatically called saved in the database (automatically called on transaction commit)on transaction commit)

Operations on Entities (2)Operations on Entities (2)

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

• Insert a new entity instance into the Insert a new entity instance into the database (SQL INSERT / UPDATE)database (SQL INSERT / UPDATE)

• Save the persistent state of the entity Save the persistent state of the entity and any owned relationship referencesand any owned relationship references

• Entity instance becomes managedEntity instance becomes managed

persist()persist()

public Customer createCustomer(int id, String public Customer createCustomer(int id, String name) {name) { Customer cust = new Customer(id, name);Customer cust = new Customer(id, name); entityManager.persist(cust);entityManager.persist(cust); return cust;return cust;} }

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

• find()find()• Obtain a managed entity instance (SQL Obtain a managed entity instance (SQL

SELECT by PK)SELECT by PK)

• Return Return nullnull if not found if not found

• remove()remove()• Delete a managed entity by PKDelete a managed entity by PK

find() and remove()find() and remove()

public void removeCustomer(Long custId) {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);}}

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

• Merges the state of detached entity into Merges the state of detached entity into a managed copy of the detached entitya managed copy of the detached entity

• Returned entity has a different Java Returned entity has a different Java identity than the detached entityidentity than the detached entity

• May invoke SQL SELECTMay invoke SQL SELECT

merge()merge()

public Customer storeUpdatedCustomer(Customer public Customer storeUpdatedCustomer(Customer cust) {cust) { return entityManager.merge(cust);return entityManager.merge(cust);} }

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

QueriesQueriesUsing JPQLUsing JPQL

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

• Dynamic or statically defined (Dynamic or statically defined (named named queriesqueries))

• Criteria using Criteria using JPQLJPQL (Java Persistence (Java Persistence API Query Language, a kind of SQL)API Query Language, a kind of SQL)

• Native SQL support (when required)Native SQL support (when required)

• Named parameters bound at execution Named parameters bound at execution time (no SQL injection)time (no SQL injection)

QueriesQueries

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

• Pagination and ability to restrict size of Pagination and ability to restrict size of resultresult

• Single/multiple-entity results, data Single/multiple-entity results, data projectionsprojections

• Bulk update and delete operation on an Bulk update and delete operation on an entityentity

• Standard hooks for vendor-specific Standard hooks for vendor-specific hintshints

Queries (2)Queries (2)

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

• Query instances are obtained from factory Query instances are obtained from factory methods on methods on EntityManagerEntityManager, e.g., e.g.

• Query API:Query API:

• getResultList()getResultList() – execute query returning – execute query returning multiple resultsmultiple results

• getSingleResult()getSingleResult() – execute query returning – execute query returning single resultsingle result

• executeUpdate()executeUpdate() – execute bulk update or – execute bulk update or deletedelete

Query APIQuery API

Query query = entityManager.createQuery(Query query = entityManager.createQuery( "SELECT e from Employee e");"SELECT e from Employee e");

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

• setFirstResult()setFirstResult() – set the first result to – set the first result to retrieveretrieve

• setMaxResults()setMaxResults() – set the maximum – set the maximum number of results to retrievenumber of results to retrieve

• setParameter()setParameter() – bind a value to a named or – bind a value to a named or positional parameterpositional parameter

• setHint()setHint() – apply a vendor-specific hint to – apply a vendor-specific hint to the querythe query

• setFlushMode()setFlushMode() – apply a flush mode to the – apply a flush mode to the query when it gets runquery when it gets run

Query API (2)Query API (2)

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

• Use Use createQuery()createQuery() factory method at factory method at runtime and pass in the JPQL query stringruntime and pass in the JPQL query string

• Use correct execution methodUse correct execution method

• getResultList(), getSingleResult(), getResultList(), getSingleResult(), executeUpdate()executeUpdate()

• Query may be compiled/checked at Query may be compiled/checked at creation time or when executedcreation time or when executed

• Maximal flexibility for query definition and Maximal flexibility for query definition and executionexecution

Dynamic QueriesDynamic Queries

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

• 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 For example, if “Account” was passed in then JPQL string would be: “then JPQL string would be: “select a from select a from Account aAccount a””

Dynamic Queries – ExampleDynamic Queries – Example

public List findAll(String entityName){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();}}

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

• Use Use createNamedQuery()createNamedQuery() factory factory method at runtime and pass in the method at runtime and pass in the query namequery name

• Query must be statically definedQuery must be statically defined

• Query names are Query names are ““globallyglobally”” scoped scoped

• Provider can to precompile the queries Provider can to precompile the queries and return errors at deployment timeand return errors at deployment time

• Can include parameters and hints in Can include parameters and hints in static query definitionstatic query definition

Named QueriesNamed Queries

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

Named Queries – ExampleNamed Queries – Example

@NamedQuery(name="Sale.findByCustId", @NamedQuery(name="Sale.findByCustId", query="select s from Sale s query="select s from Sale s where s.customer.id = :custId where s.customer.id = :custId order by s.salesDate") order by s.salesDate")

public List findSalesByCustomer(Customer cust) {public List findSalesByCustomer(Customer cust) {

return (List<Customer>)entityManager.return (List<Customer>)entityManager.

createNamedQuery("Sale.findByCustId")createNamedQuery("Sale.findByCustId")

.setParameter("custId", cust.getId()).setParameter("custId", cust.getId())

.getResultList();.getResultList();

}}

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

ORM MappingsORM MappingsAnnotations or XMLAnnotations or XML

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

• Map persistent object state to relational Map persistent object state to relational database database

• Map relationships to other entitiesMap relationships to other entities

• Metadata may be annotations or XML (or Metadata may be annotations or XML (or both)both)

Object/Relational MappingObject/Relational Mapping

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

AnnotationsAnnotations• Logical—object model (e.g. Logical—object model (e.g.

@OneToMany)@OneToMany)

• Physical—DB tables and columns (e.g. Physical—DB tables and columns (e.g. @Table)@Table)

• XMLXML• Can specify scoped settings or defaultsCan specify scoped settings or defaults

• Standard rules for default db Standard rules for default db table/column namestable/column names

Annotations / XMLAnnotations / XML

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

• State may be State may be ““fetchedfetched”” as EAGER or LAZY as EAGER or LAZY

• LAZY – container defers loading until the field LAZY – container defers loading until the field or property is accessedor property is accessed

• EAGER – requires that the field or relationship EAGER – requires that the field or relationship be loaded when the referencing entity is loadedbe loaded when the referencing entity is loaded

• Cascading of entity operations to related Cascading of entity operations to related entitiesentities

• Setting may be defined per relationshipSetting may be defined per relationship

• Configurable globally in mapping file for Configurable globally in mapping file for persistence-by-reachabilitypersistence-by-reachability

Fetching and CascadingFetching and Cascading

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

• Direct mappings of fields to columnsDirect mappings of fields to columns

• @Basic – optional, indicates simple @Basic – optional, indicates simple mapped attributemapped attribute

• Can specify fetch=EAGER / LAZYCan specify fetch=EAGER / LAZY

• Maps any of the common simple Java Maps any of the common simple Java typestypes

• Primitives, wrappers, serializable, etc.Primitives, wrappers, serializable, etc.

• Used in conjunction with @Column Used in conjunction with @Column

• Can override any of the defaultsCan override any of the defaults

Simple MappingsSimple Mappings

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

public class Customer {

int id;

String name;

int c_rating;

Image photo;}

CUSTOMER

ID NAME CREDIT PHOTO

@Entity

@Id

@Lob

@Column(name=“CREDIT”)

Simple MappingsSimple Mappings

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

Simple MappingsSimple Mappings

<entity class="example.Customer"><entity class="example.Customer">

<attributes><attributes>

<id name="id"/><id name="id"/>

<basic name="c_rating"><basic name="c_rating"> <column name="CREDIT"/> <column name="CREDIT"/> </basic> </basic>

<basic name="photo"><lob/></basic><basic name="photo"><lob/></basic>

</attributes></attributes>

</entity></entity>

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

• Common relationship mappings supportedCommon relationship mappings supported

• @ManyToOne@ManyToOne, , @OneToOne@OneToOne – single entity – single entity

• @OneToMany@OneToMany, , @ManyToMany@ManyToMany – collection – 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@JoinColumn to specify foreign key column to specify foreign key column

• @JoinTable@JoinTable decouples physical relationship decouples physical relationship mappings from entity tablesmappings from entity tables

Relationship MappingsRelationship Mappings

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

public class Sale {

int id;

...

Customer cust;}}

SALE

CUST_IDID

CUSTOMER

. . .ID

@Entity

@ManyToOne

@Id. . .

ManyToOne MappingManyToOne Mapping

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

ManyToOne MappingManyToOne Mapping

<entity class="example.Sale"><entity class="example.Sale">

<attributes><attributes>

<id name="id" /><id name="id" />

......

<many-to-one name="cust" /><many-to-one name="cust" />

</attributes></attributes>

</entity></entity>

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

public class Sale {

int id; ...

Customer cust;}

public class Customer { int id; ... Set<Sale> sales;}

CUSTOMERID . . .

SALE

CUST_IDID . . .

@Entity

@ManyToOne

@Id

@Entity

@Id

@OneToMany(mappedBy=“cust”)

OneToMany MappingOneToMany Mapping

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

OneToMany MappingOneToMany Mapping

<entity class="example.Customer"><entity class="example.Customer">

<attributes><attributes>

<id name="id" /><id name="id" />

......

<one-to-many name="sales" mapped-<one-to-many name="sales" mapped-by="cust"/>by="cust"/>

</attributes></attributes>

</entity></entity>

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

Using Persistence APIUsing Persistence APICreating JPA ApplicationsCreating JPA Applications

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

Persistence in Java SEPersistence in Java SEPersistence in Java SEPersistence in Java SE

• No deployment phaseNo deployment phase

• Application must use a Application must use a “Bootstrap API”“Bootstrap API” to obtain an EntityManagerFactoryto obtain an EntityManagerFactory

• Resource-local EntityManagersResource-local EntityManagers

• Application uses a local Application uses a local EntityTransactionEntityTransaction obtained from the obtained from the EntityManagerEntityManager

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

Entity TransactionsEntity TransactionsEntity TransactionsEntity Transactions

• Only used by resource-local Only used by resource-local EntityManagersEntityManagers

• Transaction demarcation under explicit Transaction demarcation under explicit application control using application control using EntityTransaction APIEntityTransaction API

• begin(), commit(), rollback(), isActive()begin(), commit(), rollback(), isActive()

• Underlying (JDBC) resources allocated by Underlying (JDBC) resources allocated by EntityManager as requiredEntityManager as required

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

Persistence ClassPersistence ClassPersistence ClassPersistence Class

• javax.persistence.Persistencejavax.persistence.Persistence

• Root class for bootstrapping an Root class for bootstrapping an EntityManagerEntityManager

• Locates provider service for a named Locates provider service for a named persistence unitpersistence unit

• Invokes on the provider to obtain an Invokes on the provider to obtain an EntityManagerFactoryEntityManagerFactory

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

EntityManagerFactory ClassEntityManagerFactory ClassEntityManagerFactory ClassEntityManagerFactory Class

• javax.persistence.EntityManagerFactoryjavax.persistence.EntityManagerFactory

• Obtained by the PersistanceObtained by the Persistance

• Creates EntityManager for a named Creates EntityManager for a named persistence unit or configurationpersistence unit or configuration

• In Java SE environment the persistence In Java SE environment the persistence unit configuration is defined in the unit configuration is defined in the META-INF/persistence.xmlMETA-INF/persistence.xml file file

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

Sample Configuration (Sample Configuration (META-META-INF/persistence.xmlINF/persistence.xml))Sample Configuration (Sample Configuration (META-META-INF/persistence.xmlINF/persistence.xml))

<?xml version="1.0" encoding="UTF-8"?><?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence"<persistence xmlns="http://java.sun.com/xml/ns/persistence"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">version="1.0">

<persistence-unit name="hellojpa"><persistence-unit name="hellojpa">

<class>hellojpa.Message</class><class>hellojpa.Message</class>

<properties><properties>

<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"/>

<property name="openjpa.ConnectionUserName" value=""/><property name="openjpa.ConnectionUserName" value=""/>

<property name="openjpa.ConnectionPassword" value=""/><property name="openjpa.ConnectionPassword" value=""/>

</properties></properties>

</persistence-unit></persistence-unit>

</persistence></persistence>

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

OpenJPA EnhancerOpenJPA EnhancerOpenJPA EnhancerOpenJPA Enhancer

• OpenJPA uses class files enhancerOpenJPA uses class files enhancer• Enhancements are critical for the normal Enhancements are critical for the normal

work of the OpenJPA!work of the OpenJPA!

• Provide optimal runtime performance, Provide optimal runtime performance, flexible lazy loading, and efficient, flexible lazy loading, and efficient, immediate dirty trackingimmediate dirty tracking

• Enhancement can be done at build time, Enhancement can be done at build time, during the deployment or at runtimeduring the deployment or at runtime

• To switch on runtime class enhancement To switch on runtime class enhancement use the following VM parameters:use the following VM parameters:

• OpenJPA uses class files enhancerOpenJPA uses class files enhancer• Enhancements are critical for the normal Enhancements are critical for the normal

work of the OpenJPA!work of the OpenJPA!

• Provide optimal runtime performance, Provide optimal runtime performance, flexible lazy loading, and efficient, flexible lazy loading, and efficient, immediate dirty trackingimmediate dirty tracking

• Enhancement can be done at build time, Enhancement can be done at build time, during the deployment or at runtimeduring the deployment or at runtime

• To switch on runtime class enhancement To switch on runtime class enhancement use the following VM parameters:use the following VM parameters:

-javaagent:lib/openjpa-1.0.2.jar-javaagent:lib/openjpa-1.0.2.jar

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

JPA Bootstrap – ExampleJPA Bootstrap – ExampleJPA Bootstrap – ExampleJPA Bootstrap – Example

public class Persistencepublic class PersistenceExampleExample { {

public static void main(String[] args) {public static void main(String[] args) {

EntityManagerFactory emf = PersistenceEntityManagerFactory emf = Persistence

.createEntityManagerFactory(.createEntityManagerFactory(""SomePUnitSomePUnit""););

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

}}

}}

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

Java Persistence APIJava Persistence APILive DemoLive Demo

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

IDE SupportIDE SupportIDE SupportIDE Support

• Eclipse Eclipse ““DaliDali”” project project ((http://www.eclipse.org/dalihttp://www.eclipse.org/dali))

• JPA supportJPA support

• NetBeans NetBeans ((http://community.java.net/netbeanshttp://community.java.net/netbeans))

• EJB 3.0 support including JPA (Beta 2)EJB 3.0 support including JPA (Beta 2)

• JDeveloper (JDeveloper (http://otn.oracle.com/jdevhttp://otn.oracle.com/jdev))

• EJB 3.0 support including JPA (10.1.3.1)EJB 3.0 support including JPA (10.1.3.1)

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

SummarySummarySummarySummary

• JPA emerged from best practices of existing JPA emerged from best practices of existing best of breed ORM productsbest of breed ORM products

• Lightweight persistent POJOs, no extra Lightweight persistent POJOs, no extra baggagebaggage

• Simple, compact and powerful APISimple, compact and powerful API

• Standardized object-relational mapping Standardized object-relational mapping metadata specified using annotations or XMLmetadata 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 JPA emerged from best practices of existing best of breed ORM productsbest of breed ORM products

• Lightweight persistent POJOs, no extra Lightweight persistent POJOs, no extra baggagebaggage

• Simple, compact and powerful APISimple, compact and powerful API

• Standardized object-relational mapping Standardized object-relational mapping metadata specified using annotations or XMLmetadata 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

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

Java Persistence APIJava Persistence APIJava Persistence APIJava Persistence API

Questions?Questions?Questions?Questions?

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

ExercisesExercisesExercisesExercises

1.1. Define an entity class Student which has Id, Define an entity class Student which has Id, FirstName and LastName.FirstName and LastName.

2.2. Define an entity class Course which has Id, Define an entity class Course which has Id, name and list of students.name and list of students.

3.3. Create a database matching the entity Create a database matching the entity classes. Use Apache Derby and its built-in classes. Use Apache Derby and its built-in identity columns support.identity columns support.

4.4. Create a program that listsCreate a program that lists all classes and the all classes and the students in each class.students in each class.

5.5. Create a program that adds a new class and Create a program that adds a new class and few students inside it.few students inside it.

1.1. Define an entity class Student which has Id, Define an entity class Student which has Id, FirstName and LastName.FirstName and LastName.

2.2. Define an entity class Course which has Id, Define an entity class Course which has Id, name and list of students.name and list of students.

3.3. Create a database matching the entity Create a database matching the entity classes. Use Apache Derby and its built-in classes. Use Apache Derby and its built-in identity columns support.identity columns support.

4.4. Create a program that listsCreate a program that lists all classes and the all classes and the students in each class.students in each class.

5.5. Create a program that adds a new class and Create a program that adds a new class and few students inside it.few students inside it.

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

ExercisesExercisesExercisesExercises