[go: up one dir, main page]

0% found this document useful (0 votes)
5 views99 pages

EN. Class Mapping

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views99 pages

EN. Class Mapping

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

Class mapping

Information Repositories
Oct-23 alb@uniovi.es 2
Mapping scenarios
Green Field
 It is a new project
 The design is not conditioned by previous
versions
 The mapper generates the database structure

Legacy
 We upgrade or extend an already existing system
 The database is already present and is plenty of
data
 The mapping has to be adapted to an existing DB,
probably with a convoluted design

Oct-23 alb@uniovi.es 3
Requirements of a class to be
mapped

 Plain Java classes can be mapped (POJO)


 Default constructor mandatory
 Setters/getters etc., as always
 Collections over interfaces: Set<>, List<>, etc.

 Extra information need for persistence is


added as metadata
 @Annotations
 xml

Oct-23 alb@uniovi.es 4
Oct-23 alb@uniovi.es 5
Entity
POJO Ejemplo (entity)

Oct-23 alb@uniovi.es 6
Value Type

Oct-23 alb@uniovi.es 7
@Id position Access by getter/setters
Access by attributes

The mapper does this to


load the object…

Oct-23 alb@uniovi.es 8
Oct-23 alb@uniovi.es 9
Metadata with annotations
 Add to Java 5
 @Entity, @Embeddable, @Id, etc.
 They decorate the class to map

 Comfortable for the programmer


 Compiled, implies early error detection

Oct-23 alb@uniovi.es 10
Metadata as XML, example

Oct-23 alb@uniovi.es 11
Metadata with XML
 On the file orm.xml
 This is referenced from persistence.xml

 XML override Annotations


 At deploy time an administrator can make
adjustments to improve performance
without touching the source code

Oct-23 alb@uniovi.es 12
Annotations vs XML

Oct-23 alb@uniovi.es 13
Oct-23 alb@uniovi.es 14
Categories of annotations
 Entity  Inheritance
 Database Schema  Locking
 Identity  Lifecycle
 Direct Mappings  Entity Manager
 Relationship  Queries
mappins
 Composition
Oct-23 alb@uniovi.es 15
Annotations by category

@AccessType

@OrderColumn

Oct-23 alb@uniovi.es 16
Annotations by category

@ElementCollection

Oct-23 alb@uniovi.es 17
Oct-23 alb@uniovi.es 18
Entities
 An entity represents a domain concept
 Can be associated with other entities
 Has an independent life cycle
 Has identity

 An entity is always mapped to a table


(or several in rare cases)

Oct-23 alb@uniovi.es 19
Entities
@Entity
 Marks a class as an entity

@Table (optional)
 Sets params for the table

By default the
table will be
called the same
as the class

Oct-23 alb@uniovi.es 20
Persistence of attributes
 Java types: the mapper knows how to map them
 String, Double, Long, Date, LocalDate, Integer, Short, Boolean, Byte…

 Domain Value Types:


 All the attributes will be embedded in the entity
table
 Class marked with @Embeddable, or entities’
attributes as @Embedded

 Association ends
 Foreign Key to the other entity table

 Rest of cases, serialization


 The type of the attribute must be Serializable
Oct-23 alb@uniovi.es 21
@Colum
 Influences the generation of DDL
 By default, (without @Column) each attribute in the
class is a column on the table with the same name as
in the class

Oct-23 alb@uniovi.es 22
@Column, attributes

Oct-23 alb@uniovi.es 23
@Basic

 Applies to an attribute
 Defines how the mapper will behave regarding that
attribute

 Of application to:

Oct-23 alb@uniovi.es 24
@Enumerated
 How enumerated elements are stored
 EnumType.ORDINAL
 EnumType.STRING

The column of the


table is of type
INTEGER or
VARCHAR

Oct-23 alb@uniovi.es 25
Not needed for the new types
- LocalDate

@Temporal - LocalTime
- LocalDateTime

Qualifies the final database format of


date-time related attributes java.util.Date,
java.util.Calendar, etc.
 Options: DATE, TIME, TIMESTAMP

Oct-23 alb@uniovi.es 26
Value Types
 Support additional domain concepts
 Its lifecycle depends on the owning entity
 Composition semantics

As attribute of an entity:
All value-type’s attributes are embedded in
the table for the entity

As an aggregate (UML Composition):


It takes an extra table with a foreign key to
entity’s table primary key

Oct-23 alb@uniovi.es 27
Example

Oct-23 alb@uniovi.es 28
@Embeddable
Marks a class as ValueType

Its attributes can be also set with annotations:


@Basic, @Column, @Lob, @Temporal, @Enumerated

Oct-23 alb@uniovi.es 29
@EllementCollection
Marks a collection of ValueType

Oct-23 alb@uniovi.es 30
Peculiar case
If there are more than
one attribute on the entity
of the same Value type…

… we have to force the names of


the columns to avoid repeated names
on the DDL

Oct-23 alb@uniovi.es 31
@Lob, @Transient
Large Object Binary type
of column to store big
@Lob binary types. For example
images.

Marks an attribute as non


@Transient persistent.
By default all are
persistent

Oct-23 alb@uniovi.es 32
Oct-23 alb@uniovi.es 33
Identity vs equality
Java identity

Object equality

Database identity
 Defined over the primary key of the table
 They are mapped with @Id
 All entity classes must have al least one @Identifier

The three identities there will not always be equal


The time in which they are is call “Guaranteed identity
context”, or “Persistence context”

Oct-23 alb@uniovi.es 34
Database reminder
Requirements of a key
 Can never be NULL
 Unique for each row
 Can never change

Types of keys
 Candidate
 Natural What is the best as primary key?
 Artificial (subrogate)

Oct-23 alb@uniovi.es 35
Candidate key
 Field (o combinations) that determines uniquely a row
in the table There usually are several.
If none, your table model
is badly designed

Natural key
 Candidate keys with significance for the user.
 They uses it in their day to day operations (dni, ssn, plate
number, etc.)

Artificial (subrogate) key


 Without significance in the domain, but for the system
 Always system generated
Oct-23 alb@uniovi.es 36
Drawback of natural keys…

Experience shows that they cause long-term


problems if they are used as primary keys in
tables
 Always not NULL? What if the user made a
 Will never change? typo?

 Will never repeat? As primary cannot be


changed …

Oct-23 alb@uniovi.es 37
Recommended strategy
 Always use artificial keys as primary keys
 Possible on a Green Field, but not in Legacy…

 Data type for the key


 Long forms efficient index
 But, can also be String
Anyway, always define a unique
index over the natural key to
avoid repetitions

Oct-23 alb@uniovi.es 38
Who generates the value for an
artificial key?
Alternatives:
 Provided by the user
 … by the application
 … by the mapper
 … by the database

It is not easy to guarantee a never-repeating value under


any circumstance (rollback, concurrency, etc.)

Oct-23 alb@uniovi.es 39
@Id
Marks the attribute that forms the key
 It may be a composed key:

 multiple @Id and one @IdClass, or


 one @EmbeddedId

Oct-23 alb@uniovi.es 40
Alternatives
 Provided by the user Never!

 … by the application Good, write the code…

 … by the mapper
@GeneratedValue
 … by the database

Oct-23 alb@uniovi.es 41
@GeneratedValue
 Indicates the key is subrogated and assigned
either by the mapper or the database

Oct-23 alb@uniovi.es 42
Subrogated key, generated by the database, a Long

Subrogated key, generated by the mapper

Subrogated key, UUID generated by the application, String

Oct-23 alb@uniovi.es 43
@GeneratedValue vs UUID
@GeneratedValue
Advantages
 Can be a Long, indexes well
 Frees the programmer

Disadvantages
 Unstable identity, it is not assigned until the database
FLUSH
 hashCode() and equals() must be over the natural
identity (not the generated)  natural identity without
setters

Oct-23 alb@uniovi.es 44
@GeneratedValue vs UUID
UUID
Advantages
 Generated with the new entity, stable identity
 hashCode() and equals() over a UUID, generalizable
 Unique and universal code, allows external references
 Unpredictable, improves security

Disadvantages
 36 characters, more space
 Indexes worse than a Long

Oct-23 alb@uniovi.es 45
@MappedSuperClass
Allows you to set mapping options common
to several Entities in a base class

Oct-23 alb@uniovi.es 46
@MappedSuperClass

hashCode()
and equals()
generalized
over UUID
Oct-23 alb@uniovi.es 47
Oct-23 alb@uniovi.es 48
UML implemented in Java

Essential to keep the references well crossed

Recommendation: Use an specific class

Oct-23 alb@uniovi.es 49
Multiplicity with JPA
one-to-one
many-to-many
one-to-many
They are directional
many-to-one

Oct-23 alb@uniovi.es 50
Unidirectional many to one

Oct-23 alb@uniovi.es 51
Unidirectional one to many

Oct-23 alb@uniovi.es 52
Bidirectional one to many

Oct-23 alb@uniovi.es 53
Pairing both association ends
With “mappedBy” you tell
the mapper what association
ends are paired

Oct-23 alb@uniovi.es 54
If you do not use
“mappedBy” the mapper will
interpret the associations
ends are independent (two
different associations)

Oct-23 alb@uniovi.es 55
One to one with a foreign key

“mappedBy” goes
on the class/table
that does not have
the FK

Oct-23 alb@uniovi.es 56
Bidirectional many to many

Oct-23 alb@uniovi.es 57
Oct-23 alb@uniovi.es 58
Strategies to map inheritance
Unique table for all the hierarchy
 InheritanceType.SINGLE_TABLE

A table for each non-abstract entity


 InheritanceType.TABLE_PER_CLASS

A table per each entity (abstract or not)


 InheritanceType.JOINED

Oct-23 alb@uniovi.es 59
InheritanceType.SINGLE_TABLE

Table per class hierarchy

Oct-23 alb@uniovi.es 60
InheritanceType.SINGLE_TABLE

Table per class hierarchy


All classes are persisted on a unique table with the union
of all possible columns
Extra discriminator column to distinguish the type
Advantages
 Simple and efficient
 It supports polymorphic queries
 Easy implementation
 Easy to add/remove attributes on any class

Disadvantages
 All non-common columns have to be nullable
 Nullable columns might complicate queries and make it error
prone
 There will always be empty columns (waste of space)
 Might generate tables that waste a lot of space

Oct-23 alb@uniovi.es 61
InheritanceType.SINGLE_TABLE

Table per class hierarchy


This is the default strategy of the
mapper
Mapping
 On the base class:
@Inheritance
@DiscriminatorColumn (optional)
 On each derived class
@DiscriminatorValue (optional)

Recommendation
 When derived classes add few properties and you
need efficient polymorphic queries

Oct-23 alb@uniovi.es 62
InheritanceType.SINGLE_TABLE

Table per class hierarchy

@DiscriminatorColumn,
@DiscriminatorValue are not
needed, default values are taken
by the mapper if not present

Oct-23 alb@uniovi.es 63
InheritanceType.TABLE_PER_CLASS

Table per concrete class


A table for each non-abstract class
Common properties are repeated on each table

Advantages:
 Avoid nulls

Disadvantages:
 Polymorphic associations (from the baseclass) repeat the
foreign key on each table
 Polymorphic queries are less efficient: several SELECT with a
UNION
 Changes on the base class are propagated to all the tables

Recommendation
 When polymorphic queries are not needed or critical

Oct-23 alb@uniovi.es 64
InheritanceType.TABLE_PER_CLASS

Table per concrete class


A table for each non-
abstract class
abstracta

Oct-23 alb@uniovi.es 65
InheritanceType.TABLE_PER_CLASS

Table per concrete class

This strategy is optional under


the JPA spec, it might be some
provider does not support it

Oct-23 alb@uniovi.es 66
Table per class InheritanceType.JOINED

Each class in the hierarchy, abstract or not, has its own


table
 Inheritance solved with foreign keys (joins)
 No repetition of columns

Advantages
 Relational model totally normalized
 No nulls
 Supports polymorphism
 Changes of the superclass do not affect child tables

Disadvantages
 Polymorphic queries needs joins (less performant than single
table)

Oct-23 alb@uniovi.es 67
InheritanceType.JOINED

Table per subclass

Oct-23 alb@uniovi.es 68
InheritanceType.JOINED

Table per subclass


Recommendation
 In most situations, but specially if…
 … child classes are very different in the
number of columns,
 … cannot tolerate nullable columns and
 … you need polymorphism

Oct-23 alb@uniovi.es 69
InheritanceType.JOINED

Table per subclass

Oct-23 alb@uniovi.es 70
Oct-23 alb@uniovi.es 71
Associative class mapping

In Java it is one more class,


but with composed identity

On the DB it is
a table with
extra columns

Oct-23 alb@uniovi.es 72
Associative class mapping
Alternatives
 Artificial identity
 Composed identity

Oct-23 alb@uniovi.es 73
With artificial identity

Composed unique index


on the table for extra
safety

Oct-23 alb@uniovi.es 74
Con identidad compuesta

Extra class for


composed key
metadata

oct.-23 alb@uniovi.es 75
Oct-23 alb@uniovi.es 76
Optimistic concurrency control
System transactions vs Application
transactions The optimistic
solution adds an
extra version field to
the entities

Lost update

Oct-23 alb@uniovi.es 77
Pessimistic vs Optimistic

ROLLBACK

Lock Lock Lock v1.0 v2.0 v1.0

ROLLBACK
It is no longer v1.0

Pessimistic Optimistic

oct.-23 Alberto M.F.A. alb@uniovi.es 78


Extra field for version on entities
Add information to the object to detect changes
between detached and persistent state
 Long (counter)
 Timestamp (of the last modification)

Oct-23 Alberto M.F.A. alb@uniovi.es 79


Extra field for versioning
The field for versioning is
maintained by the mapper:
 Updated for each
modification of the row
 Before row update it
checks the version on the
table and on the entity, if
they do not match throws
OptimisticLockException
(unchecked)

oct.-23 alb@uniovi.es 80
Oct-23 alb@uniovi.es 81
One to many with a Bag
If you do not need to keep insertion order
and duplicates are allowed
 Use Collection<> instead of Set<>

 More performant
 There is no need too load the collection to
do a new insertion

Oct-23 alb@uniovi.es 82
One to many with a Bag

Oct-23 alb@uniovi.es 83
One to many with a List
When the insertion order matters

No mappedBy=“…”

Esto anula actualización de este extremo

Dos @JoinColumn

Oct-23 alb@uniovi.es 84
<…>ToMany @OrderBy

List keeps the order after


the sorting
But, on the database it
lost the order

Oct-23 alb@uniovi.es 85
Bidirectional many to many
with join table

@JoinTable opcional

Oct-23 alb@uniovi.es 86
Oct-23 alb@uniovi.es 87
@ElementCollection
Collections of Value Types
 Sets, bags, lists, and maps of value
types
 Collections of @Embeddable
 Similar to OneToMany, but with
valueTypes, no Entities

Oct-23 alb@uniovi.es 88
Collections of Value Types,
limitations
They cannot be queried, persisted or updated
independently of its owning class
 Strictly privately-owned (dependent) objects.
 Semantic of composition, strong owning

There is no cascade option


 ValueTypes are always persisted, updated or
removed along with its owning class

Oct-23 alb@uniovi.es 89
Map with a Set

IMAGES

The key of ITEM_IMAGE is


composed to avoid
duplicates of the same
ITEM (a set does not admit
duplicates)

Oct-23 alb@uniovi.es 90
Map with a List

Keeps the
order
The key is composed
of ITEM_ID +
POSITION to keep
order
Oct-23 alb@uniovi.es 91
Map with a Map

Keep the maps


keyset
The key is
PROPERTIES
PROPERTIES_KEY composed of
ITEM_ID +
PROPERTIES_KEY,
duplicates are not
allowed
Oct-23 alb@uniovi.es 92
Sorted & ordered collections

 Sorted and ordered are different


 Sorted, done in memory (JVM)
Comparable o Comparator
 Ordered, done on the database
 Sorted only for SortedMap and SortedSet

Oct-23 alb@uniovi.es 93
Sorted collections
Only for SortedSet and
SortedMap (done by
the JVM)

Oct-23 alb@uniovi.es 94
Ordered collections

For any collection (except


List). Done on the
database with order by

Oct-23 alb@uniovi.es 95
Oct-23 alb@uniovi.es 96
Cascading persistence (or transitive persistence)

In parent/child relationships
(aggregates)
 Children depend on the parent
 An special case of One to Many

Handle with care!


Or do not use it at all, you will
get the same effect with a few
lines of code…

Oct-23 alb@uniovi.es 97
Tipos de cascada JPA
 ALL
 MERGE
 PERSIST
 REFRESH
 REMOVE
 DETACH

Oct-23 alb@uniovi.es 98
Delete-orphan cascade

Oct-23 alb@uniovi.es 99

You might also like