03_creating the persistence layer
TRANSCRIPT
3Copyright © 2007, Oracle. All rights reserved.
Creating the Persistence Layer
3-2 Copyright © 2007, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the following:
• Describe what is meant by persistence
• Create an Object-Relational mapping
• Use annotations to enhance Java Persistence API (JPA) Entities
• Use JPA Entities to map application data to the database
• Identify a JPA query and use it effectively in an application
• Use JDeveloper to develop and test JPA Entities
• Create a database connection in JDeveloper
3-3 Copyright © 2007, Oracle. All rights reserved.
What Is Persistence?
The persistence layer provides mapping between objects and database tables.
This layer:
• Enables portability across databases and schemas
• Supports read, write, and caching capabilities
• Protects developers from database issues
• Facilitates change and maintenance
• Should be used in any application that has an object model
3-4 Copyright © 2007, Oracle. All rights reserved.
Persistence: Overview
• Mapping relational database objects to Java objects enables easy Java EE application development.
• Frameworks such as EJB 3.0 JPA provide this object-relational mapping.
Entity/JPAPersistenceArchitecture
Java model Schema
3-5 Copyright © 2007, Oracle. All rights reserved.
Persistence Layer
A persistence layer abstracts persistence details from the application layer.
SQLRows
Objects
Persistence
Objects
Object-level querying and creation
results are objects.
Results arereturned as
raw data.
API uses SQLor databasespecific calls.
Object creation and updates through object-level API
3-6 Copyright © 2007, Oracle. All rights reserved.
What Are POJOs?
A POJO:
• Stands for Plain Old Java Object
• Does not implement any special interface
• Is not concerned with “wiring” up to a framework
• Enables developer to focus on business logic
• Contains field definitions and accessors
3-7 Copyright © 2007, Oracle. All rights reserved.
EJB 3.0 - Java Persistence API
• Lightweight POJO entity model – Portable – Simplified– Modular
• Standardized Object-Relational (O/R) mapping– Annotated– Flexible
• Dynamic queries• Full-featured EJB QL
3-8 Copyright © 2007, Oracle. All rights reserved.
JPA Entities
• Consistent persistence mechanism– Java Persistence API (JPA)
• Simple programming model– POJO persistence (Plain Old Java Interface)– Object-Relational mapping annotations– Getter/setter methods– Can contain logic (validation and so on)
• The EntityManager object– Handles data manipulation– Enables entities to be called outside the container
3-9 Copyright © 2007, Oracle. All rights reserved.
Entity Annotations
• @Entity– @Id– @IdClass– @EmbeddedId
• @Table, @SecondayTable– @UniqueConstraint– @PrimaryKeyJoinColumn(s)
• @NamedQuery(s)• Sequencing
– @GeneratedValue– @SequenceGenerator– @TableGenerator
3-10 Copyright © 2007, Oracle. All rights reserved.
How Do JPA Entities Work?
A JPA entity:
• Is a lightweight object that manages persistence data
• Is defined as a Plain Old Java Object (POJO) marked with the Entity annotation (no interfaces required)
• Must implement the java.io.Serializable interface to be passed by value to a remote application
• Is mapped to a database by using annotations
@Entity@Table(name=“PRODUCTS")
Database
@Id@Column(name=“PRODID")
POJO ORDERS
3-11 Copyright © 2007, Oracle. All rights reserved.
Java Persistence API at Work
CreateProducts
ProductsBean
EntityManager
Products table
Product object
Product entity
Insert record
Invoke persist
Invoke addProducts
3-12 Copyright © 2007, Oracle. All rights reserved.
JPA O/R Mapping
• Sensible default mapping strategies:– Use annotations to overwrite defaults.
• Collection interfaces used for relationships:– @OneToOne, @OneToMany, @ManyToOne, and so on
• Ability to map one or more persistent objects to a table:– Embeddable
• Support for typical inheritance strategies:– Single table per class hierarchy, per class, and so
on
3-13 Copyright © 2007, Oracle. All rights reserved.
Mapping Types
A mapping type addresses ways in which an object’s data and relationships are stored in the database.
• Direct-to-field: Enables data in an instance variable to be stored directly into a column in a table
• Type conversion: Enables data of one type to be stored in a table as another type– “age” may be a string in the object but stored as
NUMBER in the table.
• One-to-one: Describes how a one-to-one relationship between two classes is stored in the database
3-14 Copyright © 2007, Oracle. All rights reserved.
Specifying Object Relational (O/R) Mapping
Mapping of a JPA entity to a database table is done by default, using annotations.
@Entity // annotationpublic class Products implements Serializable
{ @Column(nullable = false) private String description; private String image; @Column(nullable = false) private String name; @Id @Column(name="PROD_ID", nullable = false) private Long prodId;
…}
PRODUCTS
PRODID (PK)
NAME
3-15 Copyright © 2007, Oracle. All rights reserved.
Mapping Relationships Between Entities
Annotations for entity relationships:
• OneToOne
• OneToMany
• ManyToMany andAssociationTable
User Address
ServiceHistory
Users Products
ServiceRequest
3-16 Copyright © 2007, Oracle. All rights reserved.
Managing Persistence of JPA Entities
• The life cycle of an entity is managed by using the EntityManager interface, which is part of the JPA.
• An entity can be created by using:– The new operator (creates detached instance)
• An entity is inserted, updated, or deleted from a database through the Java Persistence API.
new
EntityEntitiesJPA API Database
find()
Query
persist()merge()remove()
DML
3-17 Copyright © 2007, Oracle. All rights reserved.
Entity Manager
• Querying:– Retrieval of entities from the database
• Transactions:– Applying changes to entities
• General:– isOpen()– close()– contains(Object entity)
• Usage:– Container managed (injection)– Application bootstrap (EntityManagerFactory)
3-18 Copyright © 2007, Oracle. All rights reserved.
Entity Manager
Object Database
SQL statement
Query results
Retrieve records
Commit records
EntityManager
3-19 Copyright © 2007, Oracle. All rights reserved.
JPA Entity Manager
• EntityManager serves as the untyped “home”:– Access and manipulate entities– Inject using the @PersistenceContext annotation – Create a new POJO with the new keyword
• It provides life cycle operations:– persist()– remove()– merge()
• It acts as the factory for query objects.
3-20 Copyright © 2007, Oracle. All rights reserved.
Life Cycle of an Entity
Managedpersist()
Detached
merge() refresh()
Out of scope
New
Persisted
find() query()
Removed
new()
remove()
3-21 Copyright © 2007, Oracle. All rights reserved.
Persistence Context and Scope
• Manages Entity state for EntityManager
• Managed during persistence scope
• Tracks Entities when attached to transaction
Persistence Context
Transaction
Detached Entity
Entity
3-22 Copyright © 2007, Oracle. All rights reserved.
Manipulating Records with JPA
JPA Query Language (JPA QL) is a query language for dynamic and static queries expressed through metadata.
EJB
SELECT
UPDATE
DELETE
Persistence mapping
Operateson
Entity Entity
Relationship
Fields or properties
Compiled
Native SQL
Database
Annotations, deployment descriptor, or both
Mapped
3-23 Copyright © 2007, Oracle. All rights reserved.
Writing Basic JPA QL SELECT Statements
• Syntax for a JPA QL SELECT statement:
• JPA QL Named Query example:– Find all Products.
SELECT [DISTINCT] select_expressionFROM abstract_schema_name [AS] identifier_variable[WHERE conditional_expressions(s)][ORDER BY order_by_item(s)]
@NamedQuery(name = "Products.findAll", query = "select o from Products o"),
3-24 Copyright © 2007, Oracle. All rights reserved.
Creating JPA Entities
Select New > EJB > Entities fromthe Tables Wizard to:• Create a POJO for each table• Create the .java file for each
resolution for Many-to-Manyrelationships
3-25 Copyright © 2007, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
• Describe what is meant by persistence and how JPA entities implement it
• Create an object-relational mapping using annotations to enhance entity beans
• Identify a named query and use it effectively in an application
3-26 Copyright © 2007, Oracle. All rights reserved.
Practice Overview: Developing EJBs
This practice covers the following topics:
• Creating JPA entities in JDeveloper
• Adding named queries to JPA entities