bcd session 05
TRANSCRIPT
-
8/10/2019 BCD Session 05
1/52
Slide 1 of 52Ver. 1.0
Business Component Development Using EJB Technologies
In this session, you will learn to:
Define Java persistence
Describe Java Persistence API (JPA)
Define entity classes
Define key concepts of Java Persistence APIManage entity instance life-cycle states
Describe entity instance management
Deploy entity classes
Objectives
-
8/10/2019 BCD Session 05
2/52
Slide 2 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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 implementationof 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.
Examining Java Persistence
-
8/10/2019 BCD Session 05
3/52
Slide 3 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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 entityinstances
Examining Java Persistence (Contd.)
-
8/10/2019 BCD Session 05
4/52
Slide 4 of 52Ver. 1.0
Business Component Development Using EJB Technologies
The following figures show three tables in the database tier.
Object Tier / Data Tier Static and Dynamic Mapping Example
Auct ion ID Sel ler I tem StartAm oun t Increment
Auction Table
BidID Auct ion Bidder Am oun t BidTime Autho r izat ion
Bid Table
I temID Descrip t ion Image
Item Table
-
8/10/2019 BCD Session 05
5/52
Slide 5 of 52Ver. 1.0
Business Component Development Using EJB Technologies
The following figures show three entity classes in the object
tier.
Object Tier / Data Tier Static and Dynamic Mapping Example (Contd.)
-
8/10/2019 BCD Session 05
6/52
Slide 6 of 52Ver. 1.0
Business Component Development Using EJB Technologies
The following figure shows the dynamic relationship
consisting of data synchronization between the object and
data tiers.
Object Tier / Data Tier Static and Dynamic Mapping Example (Contd.)
-
8/10/2019 BCD Session 05
7/52Slide 7 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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;
910
11 /** Creates a new instance of Item */
12 public Item() {
13 }
Object Tier / Data Tier Static and Dynamic Mapping Example (Contd.)
-
8/10/2019 BCD Session 05
8/52Slide 8 of 52Ver. 1.0
Business Component Development Using EJB Technologies
14
15 public Item(String description, String image){
16 setDescription(description);
17 setImage(image);
18 }
19
20 public Integer getItemID() {
21 return itemID;
22 }
23
24 public String getDescription() {
25 return description;
26 }
Object Tier / Data Tier Static and Dynamic Mapping Example (Contd.)
-
8/10/2019 BCD Session 05
9/52Slide 9 of 52Ver. 1.0
Business Component Development Using EJB Technologies
27
28 public void setDescription(String description)
{
29 this.description = description;
30 }
3132 public String getImage(){
33 return image;
34 }
35
36 public void setImage(String image) {
37 this.image = image;
38 }
39 }
Object Tier / Data Tier Static and Dynamic Mapping Example (Contd.)
-
8/10/2019 BCD Session 05
10/52Slide 10 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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.
Introducing Java Persistence API
-
8/10/2019 BCD Session 05
11/52Slide 11 of 52Ver. 1.0
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 theentity code.
-
8/10/2019 BCD Session 05
12/52Slide 12 of 52Ver. 1.0
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 transientkeyword are not persistent.
-
8/10/2019 BCD Session 05
13/52Slide 13 of 52Ver. 1.0
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.
-
8/10/2019 BCD Session 05
14/52Slide 14 of 52Ver. 1.0
Business Component Development Using EJB Technologies
Persistent Properties (Contd.)
The method signature for single-valued persistent properties
is:Type getProperty()
void setProperty(Type type)
-
8/10/2019 BCD Session 05
15/52Slide 15 of 52Ver. 1.0
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;
}
-
8/10/2019 BCD Session 05
16/52Slide 16 of 52Ver. 1.0
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;}
-
8/10/2019 BCD Session 05
17/52Slide 17 of 52Ver. 1.0
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
-
8/10/2019 BCD Session 05
18/52Slide 18 of 52Ver. 1.0
Business Component Development Using EJB Technologies
To define an entity class, you are required to:
Declare the entity class.
Verify and override the default mapping.
Defining Entity Classes: Essential Tasks
-
8/10/2019 BCD Session 05
19/52Slide 19 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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.
Declare the Entity Class
-
8/10/2019 BCD Session 05
20/52Slide 20 of 52Ver. 1.0
Business Component Development Using EJB Technologies
8. Annotate the primary key field or the getter method.
9. Declare a public or protected no-arg constructor that takes no
parameters.
Declare the Entity Class (Contd.)
-
8/10/2019 BCD Session 05
21/52Slide 21 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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;
Declare the Entity Class (Contd.)
-
8/10/2019 BCD Session 05
22/52
Slide 22 of 52Ver. 1.0
Business Component Development Using EJB Technologies
16 }
17
18 public String getName() {
19 return name;
20 }
2122 public void setName(String name) {
23 this.name = name;
24 }
25 }
Declare the Entity Class (Contd.)
-
8/10/2019 BCD Session 05
23/52
Slide 23 of 52Ver. 1.0
Business Component Development Using EJB Technologies
The following annotations are used while verifying and
overriding the default mapping:
Table annotation
Column annotation
GeneratedValue annotation
Transient annotation
Basic and LOB annotations
Verifying and Overriding the Default Mapping
-
8/10/2019 BCD Session 05
24/52
Slide 24 of 52Ver. 1.0
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.
-
8/10/2019 BCD Session 05
25/52
Slide 25 of 52Ver. 1.0
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.
-
8/10/2019 BCD Session 05
26/52
Slide 26 of 52Ver. 1.0
Business Component Development Using EJB Technologies
Key Concepts of Java Persistence API (Contd.)
The following code snippet shows an example of using the:
This unit manages the introduction ofthe bidder and their personnel details.
jdbc/BidderDB
BidderApp.jar
com.bidder.bidderdetails
-
8/10/2019 BCD Session 05
27/52
Slide 27 of 52Ver. 1.0
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
-
8/10/2019 BCD Session 05
28/52
Slide 28 of 52Ver. 1.0
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.
-
8/10/2019 BCD Session 05
29/52
Slide 29 of 52Ver. 1.0
Business Component Development Using EJB Technologies
An entity manager is the service object that manages entity
life-cycle instances.
The four life-cycle states of an entity instance are:
New
ManagedDetached
Removed
Every entity manager is associated with a persistence
context.
A persistence context is a set of entity instances in whichthere 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.
Examining Managing Entity Instance Life-Cycle States
-
8/10/2019 BCD Session 05
30/52
Slide 30 of 52Ver. 1.0
Business Component Development Using EJB Technologies
A persistence context can have the following lifetime
scopes.
Transaction scope
Extended scope
Examining Managing Entity Instance Life-Cycle States (Contd.)
-
8/10/2019 BCD Session 05
31/52
Slide 31 of 52Ver. 1.0
Business Component Development Using EJB Technologies
The following figure shows the possible states of an entity
instance.
Examining Managing Entity Instance Life-Cycle States (Contd.)
-
8/10/2019 BCD Session 05
32/52
Slide 32 of 52Ver. 1.0
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.
-
8/10/2019 BCD Session 05
33/52
Slide 33 of 52Ver. 1.0
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:
Methods Descr ipt ion
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
i l i h l i
-
8/10/2019 BCD Session 05
34/52
Slide 34 of 52Ver. 1.0
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
PreRemovePostRemove
PreUpdate
PostUpdate
PostLoad
B i C D l U i EJB T h l i
-
8/10/2019 BCD Session 05
35/52
Slide 35 of 52Ver. 1.0
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 anentity 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 theversion number in the database is automatically
incremented.
If the version numbers did not match, an exception
javax.persistence.OptimisticLockException is thrown.
B i C t D l t U i EJB T h l i
-
8/10/2019 BCD Session 05
36/52
Slide 36 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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.
Using Entities to Interact With the Database
B i C t D l t U i EJB T h l i
-
8/10/2019 BCD Session 05
37/52
Slide 37 of 52Ver. 1.0
Business Component Development Using EJB Technologies
The following code shows entity instance management
using transaction scoped persistence context:1 @Stateful
2 public AppManagerBean implements AppManager {
3 @PersistenceContext
4 private EntityManager entityManager;
5
6 public Item createItemEntry(String description,
String image) {
7 Item item = new Item(description, image);
8 entityManager.persist(item);
9 return item;
10 }
11
Using Entities to Interact With the Database (Contd.)
B i C t D l t U i EJB T h l i
-
8/10/2019 BCD Session 05
38/52
Slide 38 of 52Ver. 1.0
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);
B i C t D l t U i EJB T h l i
-
8/10/2019 BCD Session 05
39/52
Slide 39 of 52Ver. 1.0
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) {
B i C t D l t U i EJB T h l i
-
8/10/2019 BCD Session 05
40/52
Slide 40 of 52Ver. 1.0
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) {
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
41/52
Slide 41 of 52Ver. 1.0
Business Component Development Using EJB Technologies
49 item = entityManager.find(Item.class, item.getId);
50 entityManager.remove(item); // managed instance
51 return item;
52 }
53 }
Using Entities to Interact With the Database (Contd.)
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
42/52
Slide 42 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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 andentity managers
A persistence.xml file
Deploying Entity Classes
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
43/52
Slide 43 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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
Deploying Entity Classes (Contd.)
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
44/52
Slide 44 of 52Ver. 1.0
Business Component Development Using EJB Technologies
The following figure shows persistence unit components in
default settings within an EJB-JAR.
Creating a Persistence Unit Using Default Settings
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
45/52
Slide 45 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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 persistenceunit.
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 offthe EJB-JAR root directory.
6. Create (archive) the EJB-JAR module.
Creating a Persistence Unit Using Default Settings (Contd.)
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
46/52
Slide 46 of 52Ver. 1.0
Business Component Development Using EJB Technologies
The following code shows an example of the minimal
persistence XML file:1
2
3
Creating a Persistence Unit Using Default Settings (Contd.)
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
47/52
Slide 47 of 52Ver. 1.0
Business Component Development Using EJB Technologies
The following code shows an example of a persistence XML
file denoting the use of non-default settings:1
2
3 com.acme.persistence4 jdbc/MyPartDB
5 product.xml
6 order.xml
7
8 product.jar
9 product-supplemental.jar
10 com.acme.Order
Examining a Persistence Unit Using Non Default Settings
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
48/52
Slide 48 of 52Ver. 1.0
Business Component Development Using EJB Technologies
11 com.acme.Customer
12 com.acme.Item
13
14
15
16
Examining a Persistence Unit Using Non Default Settings (Contd.)
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
49/52
Slide 49 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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.
Summary
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
50/52
Slide 50 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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 ofa persistent unit.
An entity manager is the service object which is used to create,
retrieve, update, and delete data from a database.
Summary (Contd.)
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
51/52
Slide 51 of 52Ver. 1.0
Business Component Development Using EJB Technologies
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
@PostLoadThe 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.
Summary (Contd.)
Business Component Development Using EJB Technologies
-
8/10/2019 BCD Session 05
52/52
Business Component Development Using EJB Technologies
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
ManagedDetached
Removed
A persistence context is a set of entity instances, which has a
unique entity instance for any persistence identity.
Summary (Contd.)