You are on page 1of 52

Business Component Development Using EJB Technologies

Objectives

In this session, you will learn to:


Define Java persistence
Describe Java Persistence API (JPA)
Define entity classes
Define key concepts of Java Persistence API
Manage entity instance life-cycle states
Describe entity instance management
Deploy entity classes

Ver. 1.0

Slide 1 of 52

Business Component Development Using EJB Technologies


Examining Java Persistence

The Java persistence specification is the specification of the


Java API for the management of:
Persistence.
Object/relational mapping with Java EE and Java SE.

All Java EE application servers provide an implementation


of the Java Persistence API.
Examine the Java persistence model in the following two
stages:
The first stage presents a static view of persistence.
The second stage presents the dynamic view of persistence.

Ver. 1.0

Slide 2 of 52

Business Component Development Using EJB Technologies


Examining Java Persistence (Contd.)

The tasks to be performed by an application component


developer to use the Java Persistence API are:
Define entity classes
Package and deploy the entity classes
Provide application code to create and manage entity
instances

Ver. 1.0

Slide 3 of 52

Business Component Development Using EJB Technologies


Object Tier / Data Tier Static and Dynamic Mapping Example

The following figures show three tables in the database tier.


Auction Table
Auction ID

Seller

Item

StartAmount

Increment

Auction

Bidder

Amount

BidTime

Bid Table
BidID

Authorization

Item Table
ItemID

Ver. 1.0

Description

Image

Slide 4 of 52

Business Component Development Using EJB Technologies


Object Tier / Data Tier Static and Dynamic Mapping Example (Contd.)

The following figures show three entity classes in the object


tier.

Ver. 1.0

Slide 5 of 52

Business Component Development Using EJB Technologies


Object Tier / Data Tier Static and Dynamic Mapping Example (Contd.)

The following figure shows the dynamic relationship


consisting of data synchronization between the object and
data tiers.

Ver. 1.0

Slide 6 of 52

Business Component Development Using EJB Technologies


Object Tier / Data Tier Static and Dynamic Mapping Example (Contd.)

The following code shows the implementation of an entity


class:
1 @Entity
2 public class Item {
3
4 @Id
5 @GeneratedValue
6 private Integer itemID;
7 private String description;
8 private String image;
9
10
11 /** Creates a new instance of Item */
12 public Item() {
13 }

Ver. 1.0

Slide 7 of 52

Business Component Development Using EJB Technologies


Object Tier / Data Tier Static and Dynamic Mapping Example (Contd.)
14
15
16
17
18
19
20
21
22
23
24
25
26

Ver. 1.0

public Item(String description, String image){


setDescription(description);
setImage(image);
}
public Integer getItemID() {
return itemID;
}
public String getDescription() {
return description;
}

Slide 8 of 52

Business Component Development Using EJB Technologies


Object Tier / Data Tier Static and Dynamic Mapping Example (Contd.)
27
28 public void setDescription(String description)
{
29 this.description = description;
30 }
31
32 public String getImage(){
33 return image;
34 }
35
36 public void setImage(String image) {
37 this.image = image;
38 }
39 }

Ver. 1.0

Slide 9 of 52

Business Component Development Using EJB Technologies


Introducing Java Persistence API

Java Persistence API is the specification that deals with the


way relational data are mapped to java objects and how
these objects are stored in the relational databases.
Java persistence API can be commonly used within Java SE
and Java EE environments.
The Java Persistence specification defines the static and
dynamic relationships of the persistence model by defining
the entity component and entity manager object.

Ver. 1.0

Slide 10 of 52

Business Component Development Using EJB Technologies


Introducing Java Persistence API (Contd.)

The Java Persistence specifications:


Provide a standard Object-Relational (OR) mapping.
Are not tied to the Java EE container.
Can be tested and used in the J2SE environment.
Enable the use of different entity providers without affecting the
entity code.

Ver. 1.0

Slide 11 of 52

Business Component Development Using EJB Technologies


Persistent Fields

If the entity class uses persistent fields then persistence


provider accesses an objects state by reading its variables
directly.
Adhere to the following rules, while defining a persistent
field:
Persistent fields cannot be public.
Persistent field should not be directly read by the client

All fields are persisted regardless of whether they have


been annotated with @Column.
Fields annotated with @Transient or modified with transient
keyword are not persistent.

Ver. 1.0

Slide 12 of 52

Business Component Development Using EJB Technologies


Persistent Properties

If an entity class uses persistent properties, then


persistence provider retrieves an objects state by calling its
accessor methods.
For every persistent property of the entity, there is a getter
method getProperty and a setter method setProperty.
If the defined property is of type Boolean then isProperty
method is used instead of getProperty.
While defining a persistent, the methods must be public or
protected and must follow the JavaBeans naming
convention.
The persistence annotations can be applied only on getter
methods.

Ver. 1.0

Slide 13 of 52

Business Component Development Using EJB Technologies


Persistent Properties (Contd.)

The method signature for single-valued persistent properties


is:
Type getProperty()
void setProperty(Type type)

Ver. 1.0

Slide 14 of 52

Business Component Development Using EJB Technologies


Persistent Properties (Contd.)

The following code snippet displays the use of persistent


properties:
private int id;
private String message;
@Id @Column(name = "ID")
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}

Ver. 1.0

Slide 15 of 52

Business Component Development Using EJB Technologies


Persistent Properties (Contd.)
@Column(name = "MSG")
public String getMessage()
{ return message; }
public void setMessage(String message)
{
this.message = message;
}

Ver. 1.0

Slide 16 of 52

Business Component Development Using EJB Technologies


Persistent Data Types

The data types that can be mapped, while using persistent


field or persistent properties are:
Java primitive types
Java wrappers, such as java.lang.Integer
java.lang.String
byte[] and Byte[]
char[] and Character[]
Any serializable types including but not limited to:
java.util.Date
java.sql.TimeStamp

Ver. 1.0

Slide 17 of 52

Business Component Development Using EJB Technologies


Defining Entity Classes: Essential Tasks

To define an entity class, you are required to:


Declare the entity class.
Verify and override the default mapping.

Ver. 1.0

Slide 18 of 52

Business Component Development Using EJB Technologies


Declare the Entity Class

The following steps shows a process to declare the entity


class:
1. Collect information required to declare the entity class.
2. Declare a public Java technology class.
3. If an entity instance is to be passed by value as a detached
object through a remote interface, then ensure the entity class
implements the Serializable interface.
4. Ensure the class does not define the finalize method.
5. Annotate the class with the Entity annotation.
6. Declare the attributes of the entity class.
7. You can optionally declare a set of public getter and setter
methods for every attribute declared.

Ver. 1.0

Slide 19 of 52

Business Component Development Using EJB Technologies


Declare the Entity Class (Contd.)

8. Annotate the primary key field or the getter method.


9. Declare a public or protected no-arg constructor that takes no
parameters.

Ver. 1.0

Slide 20 of 52

Business Component Development Using EJB Technologies


Declare the Entity Class (Contd.)

The following code shows an example of an entity class:


1 @Entity
2 public class Customer implements Serializable {
3 private Long custId;
4 private String name;
5
6 // No-arg constructor
7 public Customer() {}
8
9 @Id
10 public Long getCustId() {
11 return custId;
12 }
13
14 public void setCustId(Long id) {
15 custId = id;
Ver. 1.0

Slide 21 of 52

Business Component Development Using EJB Technologies


Declare the Entity Class (Contd.)
16
17
18
19
20
21
22
23
24
25

Ver. 1.0

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

Slide 22 of 52

Business Component Development Using EJB Technologies


Verifying and Overriding the Default Mapping

The following annotations are used while verifying and


overriding the default mapping:
Table annotation
Column annotation
GeneratedValue annotation
Transient annotation
Basic and LOB annotations

Ver. 1.0

Slide 23 of 52

Business Component Development Using EJB Technologies


Key Concepts of Java Persistence API

Persistent unit:
Is a set of entity classes that are controlled by EntityManager
instance in an application.
Can be defined as a logical grouping of:
Mapping metadata
Database-related configuration data

Is defined in a special configuration file named as


persistence.xml, which is added to the META-INF directory of
an arbitrary archive, such as EJB-Jar, .WAR, .EAR, or JAR file.

Ver. 1.0

Slide 24 of 52

Business Component Development Using EJB Technologies


Key Concepts of Java Persistence API (Contd.)

The persistence.xml files:


Configures which classes make up a persistence unit.
Defines the base of a persistence unit by its location.
Specifies the DataSource used.

Ver. 1.0

Slide 25 of 52

Business Component Development Using EJB Technologies


Key Concepts of Java Persistence API (Contd.)

The following code snippet shows an example of using the:


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="introduction">
<description> This unit manages the introduction of
the bidder and their personnel details.
</description>
<jta-data-source>jdbc/BidderDB</jta-data-source>
<jar-file>BidderApp.jar</jar-file>
<class>com.bidder.bidderdetails</class></persistence
-unit>
</persistence>

Ver. 1.0

Slide 26 of 52

Business Component Development Using EJB Technologies


Key Concepts of Java Persistence API (Contd.)

Entity Manager:
Is the service object that manages the entity lifecycle
instances.
Is the core object, which is used to create, retrieve, update,
and delete data from a database.
Is represented by the instance named
javax.persistence.EntityManager.

The two ways by which an EntityManager instance can be


used are:
Container-managed entity manager
Application-managed entity manager

Ver. 1.0

Slide 27 of 52

Business Component Development Using EJB Technologies


Key Concepts of Java Persistence API (Contd.)

Persistence Identity:
Is a unique value used by the container in order to map the
entity instance to the corresponding table row in the database.

Persistence Context:
Is a set of entity instances, which are unique for every
persistence entity identity.
Can have either transaction scope or extended scope.

Ver. 1.0

Slide 28 of 52

Business Component Development Using EJB Technologies


Examining Managing Entity Instance Life-Cycle States

An entity manager is the service object that manages entity


life-cycle instances.
The four life-cycle states of an entity instance are:
New
Managed
Detached
Removed

Every entity manager is associated with a persistence


context.
A persistence context is a set of entity instances in which
there is a unique entity instance for any persistence identity.
The persistent identity is a unique value used by the
persistence provider to map the entity instance to the
corresponding table row in the database.
Ver. 1.0

Slide 29 of 52

Business Component Development Using EJB Technologies


Examining Managing Entity Instance Life-Cycle States (Contd.)

A persistence context can have the following lifetime


scopes.
Transaction scope
Extended scope

Ver. 1.0

Slide 30 of 52

Business Component Development Using EJB Technologies


Examining Managing Entity Instance Life-Cycle States (Contd.)

The following figure shows the possible states of an entity


instance.

Ver. 1.0

Slide 31 of 52

Business Component Development Using EJB Technologies


Entity Instance Management

When a reference to an entity manager has been obtained,


you use the methods of entity instance to read and write to
the database.

Ver. 1.0

Slide 32 of 52

Business Component Development Using EJB Technologies


Entity Manager Methods

The complete EntityManager API provides following


methods for the three kinds of operations:
Entity life-cycle management
Database synchronization operations
Entity lookup and queries

Some of the Entity Manager methods are:

Ver. 1.0

Methods

Description

flush

Forces the synchronization of the database with entities.

find

Finds an entity instance by executing a query by primary


key on the database

Contains

Returns true if the entity instance is in the persistence


context, implying that the entity instance is managed.

merge

Merges the state of the given entity into the current


persistence context

persist

Make an entity instance managed and persistent

remove

Remove the entity instance


Slide 33 of 52

Business Component Development Using EJB Technologies


Entity Life-Cycle Callback Annotations

Every persistent event corresponds to a callback method.


These methods are shared between the persistent classes
and there listeners.
The life-cycle callbacks are invoked by the persistence
provider and not by the EJB Container.
The Java Persistence API specification defines the following
life-cycle events for the entities:
PrePersist
PostPersist
PreRemove
PostRemove
PreUpdate
PostUpdate
PostLoad
Ver. 1.0

Slide 34 of 52

Business Component Development Using EJB Technologies


Versioning

The Java Persistence API specification highlights the


addition of version numbers to the entity data.
Versioning ability has to be manually enabled by the
developer.
The version number of an entity is also looked up when an
entity is retrieved from a database.
When an entity is modified and committed to the database,
the in-memory version number is compared with the version
number currently stored in the database.
If the version numbers match, the update is allowed and the
version number in the database is automatically
incremented.
If the version numbers did not match, an exception
javax.persistence.OptimisticLockException is thrown.
Ver. 1.0

Slide 35 of 52

Business Component Development Using EJB Technologies


Using Entities to Interact With the Database

You can use entity instances and the EntityManager API to


perform the following tasks:
Create a new entry in the database.
Locate and fetch an entry from the database.
Update an entry in the database.
Delete an existing entry in the database.

Ver. 1.0

Slide 36 of 52

Business Component Development Using EJB Technologies


Using Entities to Interact With the Database (Contd.)

The following code shows entity instance management


using transaction scoped persistence context:
1
2
3
4
5
6

@Stateful
public AppManagerBean implements AppManager {
@PersistenceContext
private EntityManager entityManager;

public Item createItemEntry(String description,


String image) {
7 Item item = new Item(description, image);
8 entityManager.persist(item);
9 return item;
10 }
11

Ver. 1.0

Slide 37 of 52

Business Component Development Using EJB Technologies


Using Entities to Interact With the Database (Contd.)
12 public Item findItem(Integer key) {
13 Item item = entityManager.find(Item.class, key);
14 return item;
15 }
16
17 public Item updateItemImage(Item item) {
18 // assume item has been updated prior to method
invocation
19 Item item1 = entityManager.merge(item);
20 return item1;
21 }
22
23 public Item updateItemImage(Integer key, String
newImage) {
24 Item item = entityManager.find(Item.class, key);

Ver. 1.0

Slide 38 of 52

Business Component Development Using EJB Technologies


Using Entities to Interact With the Database (Contd.)
25 item.setImage(newImage);
26 return item;
27 }
28
29 public Item updateItemImage(Item item, String
newImage) {
30 // item is detached intance; item1 is managed
instance
31 Item item1 = entityManager.merge(item);
32 item1.setImage(newImage);
33 return item1;
34 }
35
36 public Item updateItemImage(String newImage, Item
item) {

Ver. 1.0

Slide 39 of 52

Business Component Development Using EJB Technologies


Using Entities to Interact With the Database (Contd.)
37 item.setImage(newImage); // item is detatched
instance
38 Item item1 = entityManager.merge(item); // item1 is
managed
39 return item1;
40 }
41
42 public Item deleteItem(Integer key) {
43 Item item = findItem(key);
44 entityManager.remove(item);
45 return item;
46 }
47
48 public Item deleteItem(Item item) {

Ver. 1.0

Slide 40 of 52

Business Component Development Using EJB Technologies


Using Entities to Interact With the Database (Contd.)
49
50
51
52
53

Ver. 1.0

item = entityManager.find(Item.class, item.getId);


entityManager.remove(item); // managed instance
return item;
}
}

Slide 41 of 52

Business Component Development Using EJB Technologies


Deploying Entity Classes

To deploy entity classes, you are required to create a


persistence unit.
A persistence unit is a logical grouping of all the elements
required by the container to support the persistence
management of an application.
The required components of a persistence unit are:
All managed (entity) classes
Object relational mapping metadata
Entity manager factory and entity managers
Configuration information for the entity manager factory and
entity managers
A persistence.xml file

Ver. 1.0

Slide 42 of 52

Business Component Development Using EJB Technologies


Deploying Entity Classes (Contd.)

For deployment to a Java EE application server, the


components of the persistence unit must be placed in one of
the following locations:
In a EAR file
In a EJB-JAR file
In a WAR file
In an application client JAR file

Ver. 1.0

Slide 43 of 52

Business Component Development Using EJB Technologies


Creating a Persistence Unit Using Default Settings

The following figure shows persistence unit components in


default settings within an EJB-JAR.

Ver. 1.0

Slide 44 of 52

Business Component Development Using EJB Technologies


Creating a Persistence Unit Using Default Settings (Contd.)

To create a persistence unit within in an EJB-JAR file using


the default settings for various components of the
persistence unit, adhere to the following steps:
1. If not already expanded, expand the EJB-JAR archive.
2. Create subdirectories that reflect the full qualified names of
the managed classes you need to include in the persistence
unit.
3. Copy all the classes you need into the directories created in
Step 2.
4. Create a minimal persistence.xml file.
5. Copy the persistence.xml file into the META-INF directory off
the EJB-JAR root directory.
6. Create (archive) the EJB-JAR module.

Ver. 1.0

Slide 45 of 52

Business Component Development Using EJB Technologies


Creating a Persistence Unit Using Default Settings (Contd.)

The following code shows an example of the minimal


persistence XML file:
1 <persistence>
2 <persistence-unit name="OrderManagement"/>
3 <persistence>

Ver. 1.0

Slide 46 of 52

Business Component Development Using EJB Technologies


Examining a Persistence Unit Using Non Default Settings

The following code shows an example of a persistence XML


file denoting the use of non-default settings:
1 <persistence>
2 <persistence-unit name="OrderManagement5"
transaction-type=JTA>
3 <provider>com.acme.persistence</provider>
4 <jta-data-source>jdbc/MyPartDB</jta-data-source>
5 <mapping-file>product.xml</mapping-file>
6 <mapping-file>order.xml</mapping-file>
7 <exclude-unlisted-classes/>
8 <jar-file>product.jar</jar-file>
9 <jar-file>product-supplemental.jar</jar-file>
10 <class>com.acme.Order</class>

Ver. 1.0

Slide 47 of 52

Business Component Development Using EJB Technologies


Examining a Persistence Unit Using Non Default Settings (Contd.)
11
12
13
14

<class>com.acme.Customer</class>
<class>com.acme.Item</class>
<properties>
<property name="com.acme.persistence.sql-logging"
value="on"/>
15 </properties>
16 </persistence-unit>

Ver. 1.0

Slide 48 of 52

Business Component Development Using EJB Technologies


Summary

In this session, you learned that:


All Java EE application servers are required to provide an
implementation of the Java Persistence API.
The Java persistence model can be examined in the following
two stages:
The first stage presents a static view of persistence.
The second stage presents the dynamic view of persistence.

The Java Persistence specification


Provides a standard Object-Relational (OR) mapping.
Is not tied to the Java EE container.
Can be tested and used in the J2SE environment.
Enables to use different entity providers without affecting
the entity code.

Ver. 1.0

Slide 49 of 52

Business Component Development Using EJB Technologies


Summary (Contd.)

An entity is a persistence domain object that represents a table


in a relational database.
The persistent state of an entity is represented either through
persistent fields or persistent properties.
A persistence unit is defined in a special configuration file
named as persistence.xml, which controls the configuration of
a persistent unit.
An entity manager is the service object which is used to create,
retrieve, update, and delete data from a database.

Ver. 1.0

Slide 50 of 52

Business Component Development Using EJB Technologies


Summary (Contd.)

A persistence context is a set of entity instances. These entity


instances are unique for every persistence entity identity The
Java Persistence API specification defines the following
life-cycle annotations for the entities:
@PrePersist
@PostPersist
@PreRemove
@PostRemove
@PreUpdate
@PostUpdate
@PostLoad
The Java Persistence API specification highlights the version
numbers added to the entity data that helps to avoid
over-writing other data updates accidentally. The @Version
annotation is used to enable versioning.

Ver. 1.0

Slide 51 of 52

Business Component Development Using EJB Technologies


Summary (Contd.)

To define an entity class, you are required to:


Declare the entity class.
Verify and override the default mapping.

The four life-cycle states of an entity instance are:


New
Managed
Detached
Removed

A persistence context is a set of entity instances, which has a


unique entity instance for any persistence identity.

Ver. 1.0

Slide 52 of 52

You might also like