EN. Class Mapping
EN. Class Mapping
Information Repositories
Oct-23 [email protected] 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 [email protected] 3
Requirements of a class to be
mapped
Oct-23 [email protected] 4
Oct-23 [email protected] 5
Entity
POJO Ejemplo (entity)
Oct-23 [email protected] 6
Value Type
Oct-23 [email protected] 7
@Id position Access by getter/setters
Access by attributes
Oct-23 [email protected] 8
Oct-23 [email protected] 9
Metadata with annotations
Add to Java 5
@Entity, @Embeddable, @Id, etc.
They decorate the class to map
Oct-23 [email protected] 10
Metadata as XML, example
Oct-23 [email protected] 11
Metadata with XML
On the file orm.xml
This is referenced from persistence.xml
Oct-23 [email protected] 12
Annotations vs XML
Oct-23 [email protected] 13
Oct-23 [email protected] 14
Categories of annotations
Entity Inheritance
Database Schema Locking
Identity Lifecycle
Direct Mappings Entity Manager
Relationship Queries
mappins
Composition
Oct-23 [email protected] 15
Annotations by category
@AccessType
@OrderColumn
Oct-23 [email protected] 16
Annotations by category
@ElementCollection
Oct-23 [email protected] 17
Oct-23 [email protected] 18
Entities
An entity represents a domain concept
Can be associated with other entities
Has an independent life cycle
Has identity
Oct-23 [email protected] 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 [email protected] 20
Persistence of attributes
Java types: the mapper knows how to map them
String, Double, Long, Date, LocalDate, Integer, Short, Boolean, Byte…
Association ends
Foreign Key to the other entity table
Oct-23 [email protected] 22
@Column, attributes
Oct-23 [email protected] 23
@Basic
Applies to an attribute
Defines how the mapper will behave regarding that
attribute
Of application to:
Oct-23 [email protected] 24
@Enumerated
How enumerated elements are stored
EnumType.ORDINAL
EnumType.STRING
Oct-23 [email protected] 25
Not needed for the new types
- LocalDate
@Temporal - LocalTime
- LocalDateTime
Oct-23 [email protected] 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
Oct-23 [email protected] 27
Example
Oct-23 [email protected] 28
@Embeddable
Marks a class as ValueType
Oct-23 [email protected] 29
@EllementCollection
Marks a collection of ValueType
Oct-23 [email protected] 30
Peculiar case
If there are more than
one attribute on the entity
of the same Value type…
Oct-23 [email protected] 31
@Lob, @Transient
Large Object Binary type
of column to store big
@Lob binary types. For example
images.
Oct-23 [email protected] 32
Oct-23 [email protected] 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
Oct-23 [email protected] 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 [email protected] 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.)
Oct-23 [email protected] 37
Recommended strategy
Always use artificial keys as primary keys
Possible on a Green Field, but not in Legacy…
Oct-23 [email protected] 38
Who generates the value for an
artificial key?
Alternatives:
Provided by the user
… by the application
… by the mapper
… by the database
Oct-23 [email protected] 39
@Id
Marks the attribute that forms the key
It may be a composed key:
Oct-23 [email protected] 40
Alternatives
Provided by the user Never!
… by the mapper
@GeneratedValue
… by the database
Oct-23 [email protected] 41
@GeneratedValue
Indicates the key is subrogated and assigned
either by the mapper or the database
Oct-23 [email protected] 42
Subrogated key, generated by the database, a Long
Oct-23 [email protected] 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 [email protected] 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 [email protected] 45
@MappedSuperClass
Allows you to set mapping options common
to several Entities in a base class
Oct-23 [email protected] 46
@MappedSuperClass
hashCode()
and equals()
generalized
over UUID
Oct-23 [email protected] 47
Oct-23 [email protected] 48
UML implemented in Java
Oct-23 [email protected] 49
Multiplicity with JPA
one-to-one
many-to-many
one-to-many
They are directional
many-to-one
Oct-23 [email protected] 50
Unidirectional many to one
Oct-23 [email protected] 51
Unidirectional one to many
Oct-23 [email protected] 52
Bidirectional one to many
Oct-23 [email protected] 53
Pairing both association ends
With “mappedBy” you tell
the mapper what association
ends are paired
Oct-23 [email protected] 54
If you do not use
“mappedBy” the mapper will
interpret the associations
ends are independent (two
different associations)
Oct-23 [email protected] 55
One to one with a foreign key
“mappedBy” goes
on the class/table
that does not have
the FK
Oct-23 [email protected] 56
Bidirectional many to many
Oct-23 [email protected] 57
Oct-23 [email protected] 58
Strategies to map inheritance
Unique table for all the hierarchy
InheritanceType.SINGLE_TABLE
Oct-23 [email protected] 59
InheritanceType.SINGLE_TABLE
Oct-23 [email protected] 60
InheritanceType.SINGLE_TABLE
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 [email protected] 61
InheritanceType.SINGLE_TABLE
Recommendation
When derived classes add few properties and you
need efficient polymorphic queries
Oct-23 [email protected] 62
InheritanceType.SINGLE_TABLE
@DiscriminatorColumn,
@DiscriminatorValue are not
needed, default values are taken
by the mapper if not present
Oct-23 [email protected] 63
InheritanceType.TABLE_PER_CLASS
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 [email protected] 64
InheritanceType.TABLE_PER_CLASS
Oct-23 [email protected] 65
InheritanceType.TABLE_PER_CLASS
Oct-23 [email protected] 66
Table per class InheritanceType.JOINED
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 [email protected] 67
InheritanceType.JOINED
Oct-23 [email protected] 68
InheritanceType.JOINED
Oct-23 [email protected] 69
InheritanceType.JOINED
Oct-23 [email protected] 70
Oct-23 [email protected] 71
Associative class mapping
On the DB it is
a table with
extra columns
Oct-23 [email protected] 72
Associative class mapping
Alternatives
Artificial identity
Composed identity
Oct-23 [email protected] 73
With artificial identity
Oct-23 [email protected] 74
Con identidad compuesta
oct.-23 [email protected] 75
Oct-23 [email protected] 76
Optimistic concurrency control
System transactions vs Application
transactions The optimistic
solution adds an
extra version field to
the entities
Lost update
Oct-23 [email protected] 77
Pessimistic vs Optimistic
ROLLBACK
ROLLBACK
It is no longer v1.0
Pessimistic Optimistic
oct.-23 [email protected] 80
Oct-23 [email protected] 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 [email protected] 82
One to many with a Bag
Oct-23 [email protected] 83
One to many with a List
When the insertion order matters
No mappedBy=“…”
Dos @JoinColumn
Oct-23 [email protected] 84
<…>ToMany @OrderBy
Oct-23 [email protected] 85
Bidirectional many to many
with join table
@JoinTable opcional
Oct-23 [email protected] 86
Oct-23 [email protected] 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 [email protected] 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
Oct-23 [email protected] 89
Map with a Set
IMAGES
Oct-23 [email protected] 90
Map with a List
Keeps the
order
The key is composed
of ITEM_ID +
POSITION to keep
order
Oct-23 [email protected] 91
Map with a Map
Oct-23 [email protected] 93
Sorted collections
Only for SortedSet and
SortedMap (done by
the JVM)
Oct-23 [email protected] 94
Ordered collections
Oct-23 [email protected] 95
Oct-23 [email protected] 96
Cascading persistence (or transitive persistence)
In parent/child relationships
(aggregates)
Children depend on the parent
An special case of One to Many
Oct-23 [email protected] 97
Tipos de cascada JPA
ALL
MERGE
PERSIST
REFRESH
REMOVE
DETACH
Oct-23 [email protected] 98
Delete-orphan cascade
Oct-23 [email protected] 99