Download Java Persistence API - Lecture Slides | CS 6030 and more Study notes Computer Science in PDF only on Docsity!
Java Persistence API
(JPA)
Based on the slides of Mike Keith, Oracle Corp.
- Persistence API for operating on Plain Old Java
Objects (POJO).
- Merger of expertise from TopLink, Hibernate,
JDO, EJB vendors and individuals
- Created as part of EJB 3.0 within JSR 220
- Released May 2006 as part of Java EE 5
- Integration with Java EE web and EJB containers
provides enterprise “ease of use” features
- “Bootstrap API” can also be used in Java SE
- Pluggable Container-Provider SPI
About JPA
- Part of “Glassfish” project on java.net
- RI for entire Java EE platform
- Sun and Oracle partnership
- Sun Application Server + Oracle persistence
- JPA impl called “TopLink Essentials”
- Donated by Oracle, derived from Oracle
TopLink
- All open source (under CDDL license)
- Anyone can download/use source code or
binary code in development or production
Reference Implementation
- Abstract or concrete top level Java class
- Non-final fields/properties, no-arg constructor
- No required interfaces
- No required business or callback interfaces (but you
may use them if you want to)
- Direct field or property-based access
- Getter/setter can contain logic (e.g. for validation)
- May be Serializable, but not required
- Only needed if passed by value (in a remote call)
Anatomy of an Entity
- Identifier (id) in entity, primary key in database
- Uniquely identifies entity in memory and in db
1. Simple id – single field/property
@Id int id;
2. Compound id – multiple fields/properties
@Id int id; @Id String name;
3. Embedded id – single field of PK class type
@EmbeddedId EmployeePK id;
Uses PK class
Persistent Identity
@Id @GeneratedValue int id;
- Identifiers can be generated in the database
by specifying @GeneratedValue on the
identifier
Identifier Generation
- Abstraction representing a set of “managed”
entity instances
- Entities keyed by their persistent identity
- Only one entity with a given persistent identity
may exist in the PC
- Controlled and managed by EntityManager
- Contents of PC change as a result of operations
on EntityManager API
Persistence Context
Application Persistence
Context
Entities
MyEntity A
MyEntity B
MyEntity C MyEntity a
EntityManager
MyEntity b
Entity state
Persistence Context
- Insert a new entity instance into the database
- Save the persistent state of the entity and any
owned relationship references
- Entity instance becomes managed
public Customer createCustomer(int id, String name) { Customer cust = new Customer(id, name); entityManager.persist(cust); return cust; }
persist()
- find()
- Obtain a managed entity instance with a given
persistent identity – return null if not found
- remove()
- Delete a managed entity with the given persistent
identity from the database
public void removeCustomer(Long custId) { Customer cust = entityManager.find(Customer.class, custId); entityManager.remove(cust); }
find() and remove()
- Dynamic or statically defined (named queries)
- Criteria using JP QL (extension of EJB QL)
- Native SQL support (when required)
- Named parameters bound at execution time
- Pagination and ability to restrict size of result
- Single/multiple-entity results, data projections
- Bulk update and delete operation on an entity
- Standard hooks for vendor-specific hints
Queries
- Query instances are obtained from factory
methods on EntityManager
getResultList() – execute query returning multiple results getSingleResult() – execute query returning single result executeUpdate() – execute bulk update or delete setFirstResult() – set the first result to retrieve setMaxResults() – set the maximum number of results to retrieve setParameter() – bind a value to a named or positional parameter setHint() – apply a vendor-specific hint to the query setFlushMode() – apply a flush mode to the query when it gets run
Queries
- Use createNamedQuery() factory method at
runtime and pass in the query name
- Query must have already been statically defined
either in an annotation or XML
- Query names are “globally” scoped
- Provider has opportunity to precompile the
queries and return errors at deployment time
- Can include parameters and hints in static query
definition
Named Queries
@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 entityManager.createNamedQuery( "Sale.findByCustId") .setParameter("custId", cust.getId()) .getResultList(); }
- Return all sales for a given customer
Named Queries
- Map persistent object state to relational database
- Map relationships to other entities
- Metadata may be annotations or XML (or both)
- Annotations
Logical—object model (e.g. @OneToMany)
Physical—DB tables and columns (e.g. @Table)
- XML
- Can additionally specify scoped settings or defaults
- Standard rules for default db table/column names
Object/Relational Mapping
- State or relationships may be loaded or “fetched”
as EAGER or LAZY
LAZY - hint to the Container to defer loading until the
field or property is accessed
EAGER - requires that the field or relationship be
loaded when the referencing entity is loaded
- Cascading of entity operations to related entities
- Setting may be defined per relationship
- Configurable globally in mapping file for
persistence-by-reachability
Object/Relational Mapping
Simple Mappings
- Common relationship mappings supported
@ManyToOne, @OneToOne—single entity
@OneToMany, @ManyToMany—collection of entities
- Unidirectional or bidirectional
- Owning and inverse sides of every bidirectional
relationship
- Owning side specifies the physical mapping
@JoinColumn to specify foreign key column
Relationship Mappings
public class Sale {
int id;
...
Customer cust; } }
SALE
ID CUST_ID
CUSTOMER
ID...
@Entity
@ManyToOne
@Id
...
ManyToOne Mapping
... <many-to-one name=“cust”/>
ManyToOne Mapping
Persistence in Java SE
- No deployment phase
- Application must use a “Bootstrap API” to
obtain an EntityManagerFactory
- Resource-local EntityManagers
- Application uses a local EntityTransaction
obtained from the EntityManager
- New application-managed persistence context for
each and every EntityManager
- No propagation of persistence contexts
Entity Transactions
- Only used by Resource-local EntityManagers
- Isolated from transactions in other
EntityManagers
- Transaction demarcation under explicit
application control using EntityTransaction API
begin(), commit(), rollback(), isActive()
- Underlying (JDBC) resources allocated by
EntityManager as required
javax.persistence.Persistence
javax.persistence.EntityManagerFactory
- Creates EntityManagers for a named
persistence unit or configuration
Bootstrap Classes
- Root class for bootstrapping an EntityManager
- Locates provider service for a named persistence unit
- Invokes on the provider to obtain an
EntityManagerFactory
Example
public class PersistenceProgram { public static void main(String[] args) { EntityManagerFactory emf = Persistence .createEntityManagerFactory(“SomePUnit”); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); // Perform finds, execute queries, // update entities, etc. em.getTransaction().commit(); em.close(); emf.close(); } }