Sunteți pe pagina 1din 25

Creating the Persistence Layer

1 of 38
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

2 of 38
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 of 38
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/JPA
Persistence
Architecture

Java model Schema

4 of 38
Persistence Layer

A persistence layer abstracts persistence details from the


application layer.

Object-level Object creation and


querying and creation Objects Objects updates through
results are objects. object-level API
Persistence
Results are API uses SQL
returned as Rows SQL
or database
raw data. specific calls.

5 of 38
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

6 of 38
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

7 of 38
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

8 of 38
Entity Annotations

 @Entity
– @Id
– @IdClass
– @EmbeddedId
 @Table, @SecondayTable
– @UniqueConstraint
– @PrimaryKeyJoinColumn(s)
 @NamedQuery(s)
 Sequencing
– @GeneratedValue
– @SequenceGenerator
– @TableGenerator
9 of 38
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")

@Id
@Column(name=“PRODID")
POJO ORDERS
Database

10 of 38
Java Persistence API at Work

CreateProducts Product
object
Invoke addProducts

ProductsBean Product
entity
Invoke persist

EntityManager

Insert record

Products table

11 of 38
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

12 of 38
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

13 of 38
Specifying Object Relational (O/R) Mapping

Mapping of a JPA entity to a database table is done by default,


using annotations.

@Entity // annotation
public 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

14 of 38
Mapping Relationships Between Entities

Annotations for entity relationships:


 OneToOne
User Address

ServiceRequest ServiceHistory
 OneToMany

Users Products
 ManyToMany and
AssociationTable
15 of 38
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.
persist()
merge() DML
remove()
new Query
find()
Entity Database
JPA API Entities

16 of 38
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)

17 of 38
Entity Manager

Commit SQL
records statement

Object EntityManager Database

Retrieve Query
records results

18 of 38
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.

19 of 38
Life Cycle of an Entity

Persisted

find()
new()
query()

persist() remove() Removed


New Managed

Out of scope merge()


refresh()

Detached

20 of 38
Persistence Context and Scope

 Manages Entity state for EntityManager


 Managed during persistence scope
 Tracks Entities when attached to transaction

Transaction

Persistence Entity
Context

Detached
Entity

21 of 38
Manipulating Records with JPA

JPA Query Language (JPA QL) is a query language for dynamic


and static queries expressed through metadata.

Persistence mapping
SELECT

Operates Relationship
UPDATE
on

DELETE Entity Entity


EJB Fields or properties

Native SQL Mapped

Annotations, deployment
Compiled descriptor, or both
Database

22 of 38
Writing Basic JPA QL SELECT Statements

 Syntax for a JPA QL SELECT statement:

SELECT [DISTINCT] select_expression


FROM abstract_schema_name [AS] identifier_variable
[WHERE conditional_expressions(s)]
[ORDER BY order_by_item(s)]

 JPA QL Named Query example:


– Find all Products.
@NamedQuery(name = "Products.findAll", query = "select o
from Products o"),

23 of 38
Creating JPA Entities

Select New > EJB > Entities from


the Tables Wizard to:
 Create a POJO for each table
 Create the .java file for each
resolution for Many-to-Many
relationships

24 of 38
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

25 of 38

S-ar putea să vă placă și