Você está na página 1de 74

1

Week 2
Object-Relational Mapping

ACKNOWLEDGMEN
TS
The slides in this presentation are
developed from:
Chapter 5 Object-Relational Mapping (page
125 to 159)

Beginning Java EE 7
Antonio Goncalves

Apress
3

OBJECTIVES
Interpret the basics of object-relational
mapping (ORM)in terms of how attributes
and relationships are mapped from a
domain model to a database.
Develop different mappings using JPA
annotations or XML mapping descriptors.
Investigate different ways for complex
relationship mappings.

ORM BASIC RULES


The entity class must be annotated with
@javax.persistence.Entity annotation.

Or denoted in an XML descriptor as an entity

@javax.persistence.Id annotation must


be used to denote a simple primary key.
The entity class must have a no-arg
constructor that has to be public or
protected.

The entity class may have other constructors


as well.
5

ORM BASIC RULES


The entity class must be a top-level class.

An enum or interface cannot be designated as


an entity.

The entity class must not be final.

No methods or persistent instance variables of


the entity class may be final.

If an entity instance has to be passed by


value as a detached object (e.g., through
a remote interface), the entity class must
implement the Serializable interface.
6

ORM BASIC RULES


The mapping of the Book entity

ORM BASIC RULES


Since the Book entity follows these simple
rules, the persistence provider can

Synchronise the data between the attributes


of the Book entity and the columns of the
BOOK table.
E.g. if the attribute isbn is modified by the
application, the ISBN column will be
synchronised, provided:
o
The entity is managed
o
The transaction context is set
8

CONFIGURATION BY
EXCEPTION
Unless specified differently, the container
or provider should apply the default rules.
Having to supply a configuration is the
exception to the rule.
This allows to write the minimum amount
of code to get application running.

CONFIGURATION BY
EXCEPTION

Without any annotation, the Book entity


would be treated just like a POJO and not
be persisted.
With @Entity, the entity is persisted.
With @Id, the id attribute has to be
mapped to a primary key.
For all the other attributes:

The entity name is mapped to a relational


table name
o
e.g. the Book entity the BOOK table

Attribute names are mapped to column 10

CONFIGURATION BY
EXCEPTION
JDBC rules apply for mapping Java
primitives to relational data types.

String VARCHAR(255)
Long BIGINT
Boolean SMALLINT

Default mapping rules are different


from one database to another.

A String is mapped to a VARCHAR in Derby,


but a VARCHAR2 in Oracle.
An Integer is mapped to an INTEGER in Derby
and a NUMBER in Oracle.
11

TABLE
Rules for configuration-by-exception
mapping state that the entity and the
table name are the same.
You may want to map data to a different
table, or even map a single entity to
multiple tables.
The @javax.persistence.Table
annotation makes it possible to change
the default values related to the table.
The name of the table

The catalog, and the database schema


@UniqueConstraint in conjunction with

12

TABLE
The Book entity being mapped to a T_BOOK
table

13

SECONDARY TABLE
An entity can be mapped to a single table
(primary table).
Data can be spread across multiple tables
(secondary tables).
o Using the annotation @SecondaryTable to
associate a secondary table to an entity
o Using the annotation @SecondaryTables for
several secondary tables
o Specifying for each attribute which table it
belongs to with the @Column annotation

14

SECONDARY TABLE
Attributes of the Address entity are
mapped into three different tables.

15

SECONDARY TABLE
Each table contains different attributes
but they all have the same primary key (to
join the tables together).

16

PRIMARY KEYS
In relational database a primary key
uniquely identifies each row in a table.
It comprises either a single column or set
of columns.
JPA requires entities to have an identifier
mapped to a primary key.

Uniquely identify an entity by either a single


attribute or a set of attributes (also known as
composite key);
This entitys primary key value cannot be
updated once it has been assigned.
17

PRIMARY KEYS
@javax.persistence.Id annotates an
attribute as being a unique identifier.
The value of this identifier can be
generated

Manually by the application


Automatically by the persistence provider
using the @GeneratedValue annotation.

If the @GeneratedValue annotation is not


defined, the application has to create its
own identifier by applying any algorithm
that will return a unique value.
18

PRIMARY KEYS
The Book entity with an automatically
generated identifier

19

COMPOSITE PRIMARY
K EYS
It is a good practice to designate a single
dedicated column as the primary key.
There are cases where a composite
primary key is required.

Mapping to a legacy database


Primary keys have to follow certain business
rules
o
A date and a value or a country code and a
time stamp need to be included.

For example

The CD-BookStore application needs to post


news.
The news has content, a title, and, a language
20
code.

COMPOSITE PRIMARY
K EYS
The primary key class NewsId is composed

of two attributes of type String: title and


language.
Primary key classes must include method
definitions for equals() and hashCode().
They must also be public, and have a noarg constructor.
They must implement serializable if need
to cross architectural layers (e.g.
persistence & presentation)
The primary key class is annotated with
@Embeddable.
21

COMPOSITE PRIMARY
K
EYS
The entity News embeds the primary key
class with @EmbeddedId annotation.

Every @EmbeddedId must refer to an


embeddable class
Simplified code to find an entity through
its composite primary key.
22

ATTRIBUTES
A primary key (simple or composite) is a
must an entity
An entity has all sorts of different
attributes, making up its state, that have
to be mapped to the table.
This state can include almost every Java
type:

Java primitive types


o
int, double, float, etc.
The wrapper classes of primitive java types
o
Integer, Double, Float, etc.
Arrays of bytes and characters

23

ATTRIBUTES

String, large numeric, and temporal types


o
java.lang.String
o
java.math.BigInteger,
java.math.BigDecimal, java.util.Date,
java.util.Calendar, java.sql.Date,
java.sql.Time, java.sql.Timestamp
Enumerated types and user-defined types that
implement the Serializable interface
Collections of basic and embeddable types

An entity can also have entity attributes

collections of entities, or embeddable classes.

This requires introducing relationships


between entities.

24

ATTRIBUTES
The @javax.persistence.Basic
annotation has two parameters
(optional and fetch)

The value of the attribute may be null


(optional)
The Fetch element can take two values:
o
LAZY: data should be fetched lazily
(only when the application asks for
the property)
o
EAGER: data should be fetched
eagerly (when the entity is initially 25

ATTRIBUTES
The Track entity with Lazy loading on the
wav attribute

26

ATTRIBUTES
@javax.persistence.Column annotation
defines the properties of a column.

Change the column name


Specify the column size
Authorise the column to have a null value
Authorise the column to be unique
Allow its value to be updatable or insertable
o
True (default): any attribute can be inserted
or updated in the database.
o
False: can still change the value in
memory, but it will not be synchronised
with the database
27

ATTRIBUTES
Customising mapping for the Book entity

28

ATTRIBUTES
@javax.persistence.Temporal
annotation has three possible values:
DATE, TIME, or TIMESTAMP
map java.util.Date and
java.util.Calendar
represent date, hour, or second

29

ATTRIBUTES
Annotated with @Entity, all attributes are
automatically mapped to a table.
While no need to map an attribute, use
the @javax.persistence.Transient
(@Transient) annotation or the java
transient keyword.
For example in the Customer entity,

Age can be calculated from the date of birth.


The age attribute does not need to be
mapped.
Therefore the age attribute can be transient.
30

ATTRIBUTES
The Customer entity with a Transient age

31

ATTRIBUTES
The enumeration types are now so
frequently used
The values of an enum

Are constants;
Have an implicit ordinal assignment that is
determined by the order in which they are
declared.
This ordinal cannot be modified at runtime but
can be used to store the value of the
enumerated type in the database.
32

ATTRIBUTES
In the following CreditCard entity and with
the default mapping

The ordinals assigned to the values of this


enumerated type at compile time are 0 for
VISA, 1 for MASTER_CARD, and 2 for
MERICAN_EXPRESS.
The persistence providers will map this
enumerated type to the database assuming
that the column is of type Integer.

33

ATTRIBUTES

34

ATTRIBUTES
In the following CreditCard entity and with
the default mapping

The ordinal assignment is determined by the


order in which values are declared.
If introducing a new constant to the top of the
enumeration, the values already stored in the
database will no longer match the
enumeration.

A better solution would be to store the


name of the value as a string with
@Enumerated annotation instead of
storing the ordinal.
35

ATTRIBUTES
Mapping an enumerated type with
String

36

ATTRIBUTES
@ElementCollection annotation is used
to indicate that an attribute contains a
collection of instances of basic types or
embeddables

java.util.Collection
java.util.Set
java.util.List

@CollectionTable annotation allows to


customise details of the collection table
such as its name.
37

ATTRIBUTES
The Book entity with a collection of strings
as descriptive tags

38

ATTRIBUTES
Relationship between the BOOK and the
TAG tables

39

MAPPING WITH XML


JPA also offers an XML syntax to map
entities.
Every single annotation has an XML
equivalent.
If both is used, XML overrides annotations.
(the length of the description column
(slide 42) in XML mapping will override
that declared in @Entity (slide 41)
Its a matter of taste, as the behaviour of
both is exactly the same.
Metadata (e.g. column length) can be
40
changed depending on

MAPPING WITH XML


This may be better expressed in external
XML deployment descriptors
So the code doesnt have to be modified.

41

MAPPING WITH XML


The mapping file METAINF/book_mapping.xml

42

MAPPING WITH XML


BOOK_XML_MAPPING table structure

In persistence.xml file, you need to


reference the book_mapping.xml file.
The persistence.xml defines

The entity persistence context


The database it should be mapped to
43

MAPPING WITH XML


A META-INF/persistence.xml file referring
to an external mapping file

44

EMBEDDABLES
Embeddables are objects that dont have a
persistent identity on their own.
They can be embedded only within owning
entities.
The owning entity can have collections of
embeddables or a single embeddable
attribute.
They are stored as an intrinsic part of an
owning entity and share the identity of this
entity.
Each attribute of the embedded object is 45

EMBEDDABLES
The @Embeddable annotation specifies that
Address can be embedded in another
entity class (or another embeddable).
Embeddables dont have a persistent
identity on their own

46

EMBEDDABLES
The Customer entity uses the @Embedded
annotation to specify Address is a persistent
attribute that will be stored as an intrinsic
part and share its identity.
Structure of the CUSTOMER table
with all ADDRESS attributes

47

RELATIONSHIP MAPPING
Object-oriented programming abounds
with classes and associations between
classes.
These associations link objects and allow
one object to cause another to perform an
action on its behalf.
An association has a direction

Unidirectional:
o
One object points only to another object;
o
One object can navigate toward another.
Bidirectional:
o
Both objects refer to each other;
o
One object can navigate toward another

48

RELATIONSHIP MAPPING
In Java, you use the dot (.) syntax to
navigate through objects.

customer.getAddress().getCountry()

unidirectio
nal

Bidirectional
association
represented
with two
arrows

bidirection
al

49

RELATIONSHIP MAPPING
An association also has a multiplicity (or
cardinality).
Each end of an association can specify
how many referring objects are involved in
the association.

In Java, an association that represents


more than one object uses collections of
type

java.util.Collection, java.util.Set,
java.util.List, or even java.util.Map

50

RELATIONSHIP MAPPING
A relationship has an ownership (i.e., the
owner of the relationship)

Unidirectional relationship: ownership is


implied
Bidirectional relationship: the owner has to be
specified explicitly

You then show the owning side, which


specifies the physical mapping, and the
inverse side (the non-owning side)

51

RELATIONSHIP MAPPING
A relational database is a collection of
relations (also called tables anything you
model is a table).
In JPA when you have an association
between one class and another, in the
database you will get a table reference.
This reference can be modelled in two
different ways:

Using a foreign key: a column that refers to a


key of another table.
Using a join table: an intermediate table to
hold the relationship information by storing

52

RELATIONSHIP MAPPING
A relationship using a join column or
foreign key

A relationship using a joint table

53

RELATIONSHIP MAPPING
You wouldnt use a join table to
represent a one-to-one relationship,
as this could have performance issues

For example, you always need to access


a third table to get the address of a
customer.

Join tables are generally used when


you have one-to-many or many-tomany cardinalities.
54

ENTITY RELATIONSHIP
JPA makes it possible to map associations.
An entity can be linked to another in a
relational model.
JPA has a default way of storing a relation.
JPA allows to use annotation to customise
the mapping.
The cardinality between two entities may
be:

One-to-one
One-to-many
Many-to-one
Many-to-many.

55

ENTITY RELATIONSHIP
Each respective mapping is named after
the cardinality of the source and target:

@OneToOne, @OneToMany, @ManyToOne, or


@ManyToMany

Each annotation can be used in a


unidirectional or bidirectional way.

56

ONE-TO-ONE
UNIDIRECTIONAL

A one-to-one unidirectional relationship


between entities

Has a reference of cardinality 1


Can be reached in only one direction

Assume the customer has only one


address.
It is important to navigate from the
customer toward the address.
You dont need to be able to navigate in
the opposite direction

Which customer lives at a given address


57

ONE-TO-ONE
UNIDIRECTIONAL
A Customer with one Address

58

ONE-TO-ONE
UNIDIRECTIONAL
As you see in CUSTOMER and ADDRESS,
these two entities have minimum
annotation requirements: @Entity and @Id
and @GeneratedValue for keys.
The persistence provider will map these
two entities to two tables and a foreign
key for the relationship.
A one-to-one mapping is triggered by the
fact that Address is declared an entity
and included in the Customer entity as an
attribute.
59

A relationship is automatically implied by

ONE-TO-ONE
UNIDIRECTIONAL
The CUSTOMER Table with a foreign key
pointing to the ADDRESS table

60

ONE-TO-ONE
UNIDIRECTIONAL
To customise the mapping, you can use
two annotations.
@OneToOne

It can modify some attributes of the


association itself, such as the way it has to be
fetched.

@JoinColumn

It is used to customise the join column -the


foreign key of the owning side.

61

ONE-TO-ONE
UNIDIRECTIONAL
The Customer entity with customised
relationship mapping

62

ONE-TO-ONE
UNIDIRECTIONAL
In JPA, a foreign key column is called a join
column.
The @JoinColumn annotation allows to
customise the mapping of a foreign key.
The previous example:

Renames the foreign key column to ADD_FK


Makes the relationship obligatory by refusing
the null value (nullable=false).
Gives the persistence provider a hint to fetch
the relationship lazily.
63

ONE-TO-MANY
UNIDIRECTIONAL
With a one-to-many relationship, one
source object refers to an ensemble of
target objects.
For example, a purchase order is
composed of several order lines.

64

ONE-TO-MANY
UNIDIRECTIONAL
The cardinality is multiple, and the
navigation is done only from Order toward
OrderLine.
In Java, this multiplicity is described by
the Collection, List, and Set interfaces
of the java.util package.

65

ONE-TO-MANY
UNIDIRECTIONAL
An Order contains OrderLines.

66

ONE-TO-MANY
UNIDIRECTIONAL
In the previous example, a collection of an
entity type is being used as an attribute
on this entity triggers:

A OneToMany relationship mapping by default;


One-to-many unidirectional relationships;
A join table to keep the relationship
information, with two foreign key columns.
o
One foreign key column refers to the table
ORDER;
o
The other refers to ORDER_LINE.
The join table is named ORDER_ORDER_LINE
(name of both tables separated by the
67
underscore _ symbol).

ONE-TO-MANY
UNIDIRECTIONAL
Join table between ORDER and ORDER_LINE

68

ONE-TO-MANY
UNIDIRECTIONAL
If you like to rename the default join table
and foreign key names or to customise
mapping, you can use JPA annotations to
redefine these default values.

The @JoinColumn annotation can be used to


change the foreign key columns.
The @JoinTable annotation can do the same
for the join table mapping.
The @OneToMany annotation customises the
relationship itself.
69

ONE-TO-MANY
UNIDIRECTIONAL

The Order entity with annotated One-toMany relationship

70

ONE-TO-MANY
UNIDIRECTIONAL
Structure of the join table

The default rule for a one-to-many


unidirectional relationship is to use a join
table.
To change to using foreign keys, the Order
entity has to provide a @JoinColumn
annotation instead of a @JoinTable.
71

ONE-TO-MANY
UNIDIRECTIONAL
The Order entity with a join column

72

ONE-TO-MANY
In the previous example:
UNIDIRECTIONAL
The @OneToMany annotation is overriding the

default fetch mode (turning it to EAGER instead


of LAZY).
By using @JoinColumn, the unidirectional
association is then mapped using the foreign
key strategy.
The foreign key is renamed to ORDER_FK by the
annotation and exists in the target table
(ORDER_LINE).

73

SUMMARY
The focus of this week is ORM.
With configuration by exception, not much
is required to map entities to tables.
JPA uses @Entity informs the persistence
provider that a class is an entity.
JPA uses @Id informs that an attribute is
its identifier.
JPA has a very rich set of annotations to
customise every little detail of ORM.
Elementary annotations can be used on
attributes or classes to customise the
mapping.
74

Você também pode gostar