71
1 J J ava Persistence API: ava Persistence API: Simplifying Persistence Simplifying Persistence Doris Chen Ph.D. Technology Evangelist Sun Microsystems, Inc. 1

TD_MXC_JPA_Chen

Embed Size (px)

Citation preview

Page 1: TD_MXC_JPA_Chen

1

JJava Persistence API:ava Persistence API:Simplifying PersistenceSimplifying Persistence

Doris Chen Ph.D.Technology EvangelistSun Microsystems, Inc.

1

Page 2: TD_MXC_JPA_Chen

Agenda• Java Persistence Requirements• JPA Programming Model• Persistence Context & Entity Manager • Transaction• O/R Mapping• Entity Relationships• Entity Inheritance Strategy

Page 3: TD_MXC_JPA_Chen

Java PersistenceJava PersistenceRequirementsRequirements

Page 4: TD_MXC_JPA_Chen

Java Persistence Requirements• Simplification of the persistence model

> Elimination of deployment descriptor> Most configuration is defaulted – configure by exception only

(configure only to override default)• POJO based programming/persistence model

> Simple Java classes – not EJB components, only 1 file instead of 3> Entities usable outside the container

> No need for Data Transfer Objects > Facilitates testability outside of the containers

• Standardized object/relational mapping> Standardized annotations @ and XML configuration files

> xml for mapping is optional• Domain modelling through inheritance and polymorphism• Extensive querying capabilities

Page 5: TD_MXC_JPA_Chen

Common Java Persistence BetweenJ2SE and J2EE Environments

• Persistence API expanded to include use outside of EJB container

• Evolved into “common” Java persistence API> You can use new Java persistence API in Java SE, Web, and

EJB applications• Support for pluggable, third-party

persistence providers> Through persistence.xml

Page 6: TD_MXC_JPA_Chen

What is an Entity?What is an Entity?

Page 7: TD_MXC_JPA_Chen

What is an Entity?

• Plain Old Java Objects (not an EJB)> Created by means of new keyword

• No required interfaces• Has a persistence identity• May have both persistent and non-persistent state

> Simple types (e.g., primitives, wrappers, enums)> Composite dependent object types (e.g., Address)> Non-persistent state (transient or @Transient)

• Can extend other entity and non-entity classes• Serializable; usable as detached objects in other tiers

> No need for data transfer objects

Page 8: TD_MXC_JPA_Chen

Entity Example@Entitypublic class Customer implements Serializable {

@Id protected Long id;protected String name;@Embedded protected Address address;protected PreferredStatus status;@Transient protected int orderCount;

public Customer() {}

public Long getId() {return id;}protected void setId(Long id) {this.id = id;}

public String getName() {return name;}public void setName(String name) {this.name = name;}

…}

Annotated as “Entity” @Id denotes primary key

Page 9: TD_MXC_JPA_Chen

Entity Identity• Every entity has a persistence identity

> Maps to primary key in database• Identity can be application or database generated• Can correspond to simple type

> @Id—single field/property in entity class> @GeneratedValue—value can be generated automatically

using various strategies (SEQUENCE, TABLE, IDENTITY, AUTO)

• Can correspond to user-defined class> @EmbeddedId—single field/property in entity class> @IdClass—corresponds to multiple Id fields in entity class

• Must be defined on root of entity hierarchy or mapped superclass

Page 10: TD_MXC_JPA_Chen

Types of Identity• Simple

> @Id – single field/property in entity class> @GeneratedValue

• User defined: > @EmbeddedId – single field/property in entity class

> @IdClass – corresponds to multiple id field in entity class

@Id @GeneratedValue(strategy=SEQUENCE)private int id;

@EmbeddedId private EmployeePK pk;

@Entity @IdClass(EmployeePK.class)public class Employee {

@Id private String empName;@Id private int dept;

Class must be@Embeddable

Page 11: TD_MXC_JPA_Chen

JPA JPA Programming ModelProgramming Model

Page 12: TD_MXC_JPA_Chen

Java Persistence Programming Model

• Entity is a POJO (no need to implement EntityBean)• Use of Annotation to denote a POJO as an entity (instead

of deployment descriptor)// @Entity is an annotation// It annotates Employee POJO class to be Entity@Entity public class Employee { // Persistent/transient fields // Property accessor methods // Persistence logic methods}

Page 13: TD_MXC_JPA_Chen

Persistence Entity Example @Entity public class Customer { private Long id; private String name; private Address address; private Collection<Order> orders = new HashSet();

public Customer() {}

@Id public Long getID() { return id; } protected void setID (Long id) { this.id = id; }

...

Annotated as “Entity”

Getters/setters to access state

@Id denotes primary key

Page 14: TD_MXC_JPA_Chen

Persistence Entity Example (Contd.)...

// Relationship between Customer and Orders @OneToManypublic Collection<Order> getOrders() { return orders;}

public void setOrders(Collection<Order> orders) { this.orders = orders;}

// Other business methods...

}

Page 15: TD_MXC_JPA_Chen

Client View: From Stateless Session Bean@Stateless public class OrderEntry {

// Dependency injection of Entity Manager for // the given persistence unit@PersistenceContextEntityManager em;

public void enterOrder(int custID, Order newOrder){

// Use find method to locate customer entity Customer c = em.find(Customer.class, custID); // Add a new order to the Orders c.getOrders().add(newOrder); newOrder.setCustomer(c); }

// other business methods}

Page 16: TD_MXC_JPA_Chen

Client Code: From Java SE Client

public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeService"); EntityManager em = emf.createEntityManager(); Collection emps = em.createQuery("SELECT e FROM Employee e") .getResultList();

// More code

Page 17: TD_MXC_JPA_Chen

Demo Demo

Creating Entities from ExistingCreating Entities from ExistingDatabase tablesDatabase tables

Page 18: TD_MXC_JPA_Chen

Persistence Context &Persistence Context &Entity ManagerEntity Manager

Page 19: TD_MXC_JPA_Chen

Persistence – Key Concepts

Persistence

EntityManager

EntityManagerFactory

PersistenceContext

PersistenceUnit

creates

creates

Configured by

Manages

Page 20: TD_MXC_JPA_Chen

Persistence Context

• Set of managed entities, belonging to a single persistence unit

• “Entity instance is in managed state”means it is contained in a persistent context

• Inclusion or exclusion of an entity into/from the persistence context will determine the outcome of any persistence operation on it

• Not directly accessible to application, it is accessed indirectly through entity manager – type of entity manager determines how a persistence context is created and removed

Page 21: TD_MXC_JPA_Chen

EntityManager• API to manage the entity instance lifecycle• Allows your program to interact with underlying

persistence engine• Similar in functionality to Hibernate Session,

JDO PersistenceManager, etc.• Provides the following functionalities

> Lifecycle operations – persist(), remove(), refresh(), merge()> Finder – find(), getReference()> Factory for query objects – createNamedQuery(),

createQuery(), createNativeQuery()> Managing persistence context – flush(), clear(), close(),

getTransaction(), ...

Page 22: TD_MXC_JPA_Chen

Entity Lifecycle State Diagram

New Detached

Removed

Managedpersist()

merge()

remove()

UpdatesPC ends

> New entity instance is created> Entity is not yet managed or persistent

> Entity becomes managed> Entity becomes persistent

in database on transaction commit

new()

> Entity is removed> Entity is deleted from

database on transaction commit

> State of detached entity is merged back into managed entity

no longer associated with persistence context

Page 23: TD_MXC_JPA_Chen

Persist Operation

public Order createNewOrder(Customer customer) {Order order = new Order(customer);

// Transitions new instances to managed. On the // next flush or commit, the newly persisted // instances will be inserted into the datastore.

entityManager.persist(order);

return order;}

Page 24: TD_MXC_JPA_Chen

Find and Remove Operations

public void removeOrder(Long orderId) {Order order =

entityManager.find(Order.class, orderId);

// The instances will be deleted from the datastore // on the next flush or commit. Accessing a // removed entity has undefined results.

entityManager.remove(order);}

Page 25: TD_MXC_JPA_Chen

Merge Operation

public OrderLine updateOrderLine(OrderLine orderLine) {

// The merge method returns a managed copy of // the given detached entity. Changes made to the // persistent state of the detached entity are // applied to this managed instance.

return entityManager.merge(orderLine);}

Page 26: TD_MXC_JPA_Chen

TransactionsTransactions

Page 27: TD_MXC_JPA_Chen

Transaction Types• Two different transaction types

> Resource-local transactions> JTA (Java Transaction API)

> Multiple participating resources> Distributed XA transactions

• Transaction type is defined in persistence unit (persistence.xml file)> Default to JTA in a JavaEE environment and to

RESOURCE_LOCAL in a JavaSE environment• Container managed entity manager use JTA transactions

> Propagation of persistence context with a JTA transaction is supported by the container – sharing same persistence context among multiple entity managers

Page 28: TD_MXC_JPA_Chen

@TransactionAttribute Annotation• TransactionAttributeType.REQUIRED• TransactionAttributeType.REQUIRES_NEW• TransactionAttributeType.MANDATORY• TransactionAttributeType.NOT_SUPPORTED• TransactionAttributeType.NEVER• TransactionAttributeType.SUPPORTS

Page 29: TD_MXC_JPA_Chen

Transactions & Persistence Context

• Transactions define when new, modified, or removed entities are synchronized with the database

• How persistence context is created and used is determined by Transaction type (Resource-local or JTA) and Transaction attribute (REQUIRED or ..)

Page 30: TD_MXC_JPA_Chen

Transaction & Persistence Context Example @Statelesspublic class AuditServiceBean implements AuditService { @PersistenceContext(unitName="EmployeeService") private EntityManager em; @TransactionAttribute(TransactionAttributeType.REQUIRED) //Default public void logTransaction(int empId, String action) { // verify employee number is valid if (em.find(Employee.class, empId) == null) { throw new IllegalArgumentException("Unknown employee id"); } LogRecord lr = new LogRecord(empId, action); em.persist(lr); }

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void logTransaction2(int empId, String action) { logTransaction(empId, action); }

Page 31: TD_MXC_JPA_Chen

Transactions & Persistence Context Example@Statelesspublic class EmployeeServiceBean implements EmployeeService { @PersistenceContext(unitName="EmployeeService") private EntityManager em; @EJB AuditService audit; public void createEmployee(Employee emp) { em.persist(emp); audit.logTransaction(emp.getId(), "created employee"); }

public void createEmployee2(Employee emp) { em.persist(emp); audit.logTransaction2(emp.getId(), "created employee"); }

Page 32: TD_MXC_JPA_Chen

Detached EntitiesDetached Entities

Page 33: TD_MXC_JPA_Chen

Detached Entities

• Must implement Serializable interface if detached object has to be sent across the wire

• No need for DTO (Data Transfer Object) anti-design pattern

• Merge of detached objects can be cascaded

Page 34: TD_MXC_JPA_Chen

Transition to Detached Entities

• When a transaction is committed or rollback'ed• When an entity is serialized

Page 35: TD_MXC_JPA_Chen

O/R MappingO/R Mapping

Page 36: TD_MXC_JPA_Chen

Object/Relational Mapping

• Comprehensive set of annotations defined for mapping> Relationships> Joins> Database tables and columns> Database sequence generators> Much more

• Specified using > Annotations within the code> Separate mapping file

Page 37: TD_MXC_JPA_Chen

37

Object/Relational Mapping● Logical and physical mapping views

● Logical—object model (e.g., @OneToMany)● Physical—DB tables and columns (e.g., @Table)

● Support for basic, serialized objects and LOBs● Unary, n-ary relationship mappings● Rules for defaulting of DB table and

column names● Access to object state using fields or properties● Multiple tables, composite relationship keys

Page 38: TD_MXC_JPA_Chen

38

Simple Mappings

● Direct mappings of fields to columns● @Basic—known field type maps to standard

DB column type● @Lob—field typically maps to BLOB or CLOB

DB column type● Used in conjunction with @Column

(physical mapping annotation)● Defaults to the type deemed most appropriate

if no mapping annotation is present● Can override any of the defaults

Page 39: TD_MXC_JPA_Chen

39

Simple Mappings

CUSTOMERID NAME C_RATING PHOTO

@Entity(access=FIELD)

@Id

@Lob

public class Customer {

int id;

String name; int c_rating;

Image photo;}

Page 40: TD_MXC_JPA_Chen

40

public class Customer {

int id;

String name;

int c_rating;

Image photo;}

Simple Mappings

@Entity(access=FIELD)

@Column(name=“CREDIT”)

@Id

@Lob

CUSTOMERID NAME CREDIT PHOTO

Mapping defaults to matching column name. Only configure if entity field and table column names are different

Page 41: TD_MXC_JPA_Chen

EntityEntityRelationshipsRelationships

Page 42: TD_MXC_JPA_Chen

Entity Relationships• Model instance association between entities• Supports unidirectional as well as bidirectional

relationships> Unidirectional relationship: Entity A references B, but B doesn't

reference A• Mapping defaults are specified for all bi-directional as well

as uni-directional cardinalities• Cardinalities

> One to one> One to many> Many to one> Many to many

Page 43: TD_MXC_JPA_Chen

Relationship Mappings – ManyToMany

public class Customer { int id; ...

Collection<Phone> phones;}

PHONES_IDCUSTS_ID

@Entity(access=FIELD) @Entity(access=FIELD)

@Id @Id

@ManyToMany @ManyToMany(mappedBy=“phones”)

public class Phone { int id; ...

Collection<Customer> custs;}

CUSTOMERID . . .

PHONEID . . .

CUSTOMER_PHONE

Join table name is made up of the 2 entities. Field name is the name of the entity plus the name of the PK field

ID

Inverseof Relationship

ownerof Relationship

Page 44: TD_MXC_JPA_Chen

Entity Relationships: ExampleMany to many – Owning side

@Entitypublic class Project {

private Collection<Employee> employees;@ManyToManypublic Collection<Employee> getEmployees() {

return employees;}

public void setEmployees(Collection<Employee> employees) {

this.employees = employees;}

...}

Page 45: TD_MXC_JPA_Chen

Entity Relationships: ExampleMany to many – Inverse side@Entitypublic class Employee {

private Collection<Project> projects;@ManyToMany(mappedBy="employees")public Collection<Project> getProjects() {

return projects;}

public void setProjects(Collection<Project> projects) {this.projects = projects;

}...}

Page 46: TD_MXC_JPA_Chen

Entity Relationships and Cascading Behavior

• Cascading is used to propagate the effect of an operation to associated entities

• Cascading operations will work only when entities are associated to the persistence context> If a cascaded operation takes place on detached entity,

IllegalArgumentException is thrown• Cascade=PERSIST• Cascade=REMOVE

> Not advisable to use it on relationships other than one-to-one and one-to-many relationships

• Cascade=MERGE Cascade=REFRESH• Cascade=ALL

Page 47: TD_MXC_JPA_Chen

Entity InheritanceEntity Inheritance

Page 48: TD_MXC_JPA_Chen

Entity Inheritance

• Entities can now have inheritance relationship> They are POJO's

• Three inheritance mapping strategies (mapping entity inheritance to database tables)> Single table – all classes stored in the same table> Joined subclass – each class is stored in a separate

table> Table per class – each concrete class is stored in a

separate table• Use Java application @Inheritance(..) to specify

mapping

Page 49: TD_MXC_JPA_Chen

Object Model

AirAnimal

wingSpan: int

LandAnimal

legCount: int

Animal

id: intname: String

Page 50: TD_MXC_JPA_Chen

Data ModelsSingle table:

ANIMALID NAME

LAND_ANMLID LEG_COUNT

AIR_ANMLID WING_SPAN

Joined:

Table per Class: LAND_ANMLID LEG_COUNT

AIR_ANMLID WING_SPANNAMENAME

ANIMALLEG_CNTID DISC NAME WING_SPAN

each class is stored in a separate table

each concrete class is stored in a separate table

all classes stored in the same table

Page 51: TD_MXC_JPA_Chen

Entity Inheritance - Mapping Classes to Tables

• Use Java application metadata to specify mapping Support for various inheritance mapping strategies

> SINGLE_TABLE [default]> All the classes in a hierarchy are mapped to a single table> Root table has a discriminator column whose value identifies the specific

subclass to which the instance represented by row belongs> TABLE_PER_CLASS

> Each class in a hierarchy mapped to a separate table and hence, all properties of the class (incl. inherited properties) are mapped to columns of this table

> JOINED> The root of the hierarchy is represented by a single table> Each subclass is represented by a separate table that contains fields specific to

the subclass as well as the columns that represent its primary key(s)

Page 52: TD_MXC_JPA_Chen

Single Table Strategy

• All the classes in a hierarchy are mapped to a single table• Annotation to the parent Entity

> @Inheritance(strategy=InheritanceType.SINGLE_TABLE)• Root table has a discriminator column whose value identifies

the specific subclass to which the instance represented by row belongs> @DiscriminatorColumn(columnDefinition="MYDTYPE")

Page 53: TD_MXC_JPA_Chen

Single Table Strategy Example // Parent Entity@Entity@Inheritance(strategy=InheritanceType.SINGLE_TABLE) //default is SINGE_TABLE

public class Person implements Serializable {...}private String name;

// Child Entity@Entitypublic class Student extends Person {...}

private String school;private double grade;

// Child Entity@Entitypublic class Teacher extends Person {...}

Page 54: TD_MXC_JPA_Chen

Single Table Strategy Example

Page 55: TD_MXC_JPA_Chen

Single Table Strategy Example

Page 56: TD_MXC_JPA_Chen

Joined Strategy

• The root of the hierarchy is represented by a single table• Each subclass is represented by a separate table that contains

fields specific to the subclass as well as the columns that represent its primary key(s)

• Annotation to the parent Entity> @Inheritance(strategy=InheritanceType.JOINED)

Page 57: TD_MXC_JPA_Chen

Joined Table Strategy Example // Parent Entity@Entity@Inheritance(strategy=InheritanceType.JOINED)@DiscriminatorColumn(columnDefinition="MYDTYPE")public class Person implements Serializable {...}

private String name;

// Child Entity@Entitypublic class Student extends Person {...}

private String school;private double grade;

// Child Entity@Entitypublic class Teacher extends Person {...}

Page 58: TD_MXC_JPA_Chen

Demo Demo

Use different strategies for Use different strategies for inheritance and how database inheritance and how database tables are createdtables are created

- SINGLE_TABLE - SINGLE_TABLE - JOINED - JOINED

Page 59: TD_MXC_JPA_Chen

Entity Inheritance Strategy

• SINGLE_TABLE [default]> All the classes in a hierarchy are mapped to a single table> This strategy provides good support polymorphic relationships between

entities and queries that cover the entire class hierarchy> May contain null fields for some subclass data

• TABLE_PER_CLASS > Each class in a hierarchy mapped to a separate table and hence,

provides poor support for polymorphic relationships> requires SQ union or separate SQL queries for each subclass

• JOINED> no null fields => compact data> This provides good support for polymorphic relationships, but requires

one or more join operations – may result in poor performance

Page 60: TD_MXC_JPA_Chen

Embedded Objects Embedded Objects

Page 61: TD_MXC_JPA_Chen

Embedded Objects

• @Embeddable used to mark an embeddable object• Embeddable object is stored as intrinsic part of an owning

entity> Doesn't have its own identity

• Each persistent field/property of embeddable object is mapped to the same database table that represents the owning entity

Page 62: TD_MXC_JPA_Chen

Embedded Objects

public class Customer {

int id;

CustomerInfo info;}

CUSTOMERID NAME CREDIT PHOTO

public class CustomerInfo { String name; int credit;

Image photo;}

@Entity

@Embedded

@Id

@Embeddable

@Lob

Page 63: TD_MXC_JPA_Chen

Entity ListenersEntity Listeners

Page 64: TD_MXC_JPA_Chen

Entity Listeners

• Listeners or callback methods are designated to receive invocations from persistence provider at various stages of entity lifecycle

• Callback methods > Annotate callback handling methods right in the entity class or

put them in a separate listener class> Annotations

> PrePersist / PostPersist> PreRemove/ PostRemove> PreUpdate / PostUpdate> PostLoad

Page 65: TD_MXC_JPA_Chen

Entity Listeners: Example – 1@Entity@EntityListener(com.acme.AlertMonitor.class)public class AccountBean implements Account {

Long accountId;Integer balance;boolean preferred;public Long getAccountId() { ... }public Integer getBalance() { ... }

@Transient contextpublic boolean isPreferred() { ... }

public void deposit(Integer amount) { ... }public Integer withdraw(Integer amount) throws NSFException {... }

Page 66: TD_MXC_JPA_Chen

Entity Listeners: Example – 2

@PrePersistpublic void validateCreate() {

if (getBalance() < MIN_REQUIRED_BALANCE)throw new AccountException("Insufficient balance to

open an account");}

@PostLoadpublic void adjustPreferredStatus() {

preferred =(getBalance() >= AccountManager.getPreferredStatusLevel());

}}

Page 67: TD_MXC_JPA_Chen

Entity Listeners: Example – 3

public class AlertMonitor {

@PostPersistpublic void newAccountAlert(Account acct) {

Alerts.sendMarketingInfo(acct.getAccountId(), acct.getBalance());

}}

Page 68: TD_MXC_JPA_Chen

Summary,Summary,Resources,Resources,Sun Developer NetworkSun Developer Network

Page 69: TD_MXC_JPA_Chen

• Simplifies persistence model• Supports Light-weight persistence model• Support both Java SE and Java EE environments• O/R mapping through annotation• Extensive querying capabilities

Java Persistence Summary

Page 70: TD_MXC_JPA_Chen

Resourceshttp://developers.sun.com/events/techdays/presentations/

• Glassfish persistence homepage> https://glassfish.dev.java.net/javaee5/persistence

• Persistence support page> https://glassfish.dev.java.net/javaee5/persistence/entity-

persistence-support.html• Blog on using persistence in Web applications

> http://weblogs.java.net/blog/ss141213/archive/2005/12/using_java_pers.html

• Blog on schema generation> http://blogs.sun.com/roller/page/java2dbInGlassFish#automatic

_table_generation_feature_in

Page 71: TD_MXC_JPA_Chen

71

JJava Persistence API:ava Persistence API:Simplifying PersistenceSimplifying Persistence

Doris Chen Ph.D.Technology EvangelistSun Microsystems, Inc.

71