Third lecture in Java EE training series.
Covers:
- JPA entities and persistence units
- Mapping of JPA entities to SQL database
- Querying entities
- Lazy and eager loading
- Id generation
- Optimistic locking
2. Contents
●JPA entities and persistence units
●Mapping of JPA entities to SQL database
●Querying entities
●Lazy and eager loading
●Id generation
●Optimistic locking
3. JPA entities
●An entity is a lightweight persistence domain object
●Typically, an entity represents a table in a relational
database, and each entity instance corresponds to a
row in that table
●fields or properties use object/relational mapping
annotations to map the entities and entity
relationships to the relational data
4. Requirements for Entity Classes
●javax.persistence.Entity annotation
●Constructor without arguments
●Persistent values properties/fields may be of:
l
Java primitive values, their wrappers and String
l
Other Java standard number or datetime types
l
Enums, byta and char arrays
l
Other entities, collections of entities, embeddable
classes
5. Entity persistence type
●Persistent Fields
l
Mapped Fields are accessed directly
●Persistent Properties
l
Properties mapped via getter method accessed via
setter/getter according to Java Beans convention
●Transient fields/properties
l
marked by transient or @Transient
l
their state is not saved to database
6. Validating integrity of JPA entities
●Annotations of Java Bean Validation may be
used to ensure integrity before committing
transaction
l
javax.validation.constraints package
●Most used constraints:
l
@NotNull, @Pattern, @Past
7. Persistence Unit
●Persistence is turned on by presence of valid
persistence.xml in META-INF directory
●persistence.xml defines groups of entities together
with connection parameters
●Persistence unit represents a database
●Persistence context is tied to a persistence unit and
represents a single connection to the database
8. Types of definition of connection
information
●Transaction-type
l
JTA – datasource to the DB and transaction are
configured and handled by the application server –
the datasource is provided by specified JNDI name
in element jta-data-source
l
RESOURCE_LOCAL – connection information is
specified directly and transactions are controlled by
calling of appropriate methods
9. Entity Manager
●Component that represents single connection
●API to control persistence context of JPA entities,
search JPA entities and provide means to query DB
and execute batch statements
●Entity Manager Factory
l
Represents information to reate connetions
l
Can be used to create Entity Managers
l
Provides information about database metadata
10. Lifecycle of a JPA entity
●to be
synchronized
with a DB, entity
must be
attached to an
Entity Manager
11. Mapping of entities
●Entity must be included in a persistence-unit
●Annotated by @Entity
●Must have a primary key specified
●All fields/properties of an entity are mapped to DB
l
Unless marked as transient or with @Transient
annotation
●Name of columns in DB are inferred from
field/property names
12. Mapping of entities – primitive types
●Primitive types are automatically mapped to a
column of appropriate SQL type
l
String to VARCHAR
l
Numbers to NUMERIC, DECIMAL, …
l
Boolean to BOOLEAN, NUMERIC
●To refine mapping, additional JPA annotations are
needed (@Lob, @Column)
13. Mapping of entities – date and time
●Mapping of Date and Calendar
●Needs annotation Temporal, with definition of
type of data:
l
DATE
l
TIME
l
TIMESTAMP
14. Mapping of entities – enumerations
●Need to use @Enumerated
●Two options how to map to DB:
l
ORDINAL – not stable enum values are
added/removed
l
STRING – not very convenient, if we want to
map by id or to an existing enumeration table
15. Mapping of entities – collections
●According to direction
l
Uni-directional vs. Bi-directional
●According to cardinality
l
@OneToOne
l
@OneToMany
l
@ManyToOne
l
@ManyToMany (intermediary table is generated)
16. Mapping of entities – bi-directional
relations
●Only one direction is mapped to a column
l
@JoinColumn overwrites default mapping
●Reverse direction is mapped to a Java field in the
other entity
●In case of OneToOne and ManyToMany, annotations
on both references
●Otherwise OneToMany is in one entity, ManyToOne
in the other entity
17. Mapping of entities – collections of
primitive types
●Need to use @ElementCollection
●A separate table to hold values of collection is
generated
18. Mapping of entities – difference
between collection types
Collection type Description
List Ordered list of elements. Order is either not persisted, or
defined by additional integer column in DB. Only unique
elements are stored in DB.
Set Unordered collection of elements. Ensures that elements are
unique. Very close to how data is stored in DB.
Collection Similar to List, but can be represented also by a Set
Map Essentially a Set of keys with attached values, not much
used in practice
19. Customization of DB mapping
●JPA listeners
●
@PrePersist, @PreRemove, @PostPersist,
@PostRemove, @PreUpdate,
@PostUpdate, @PostLoad
20. Customization of DB mapping
●Converters – new in Java EE 7
l
@Convert to specify converter class
l
Converter class implements
AttributeConverter
l
Converter class must be mentioned in
orm.xml
21. Queries
●Two standard ways:
l
JPQL – text-based queries similar to SQL
l
Criteria – Java object based queries with
syntax check and strict typing
●Also possible to execute a direct SQL query
22. JPQL
●SELECT b FROM Book b WHERE b.name like
'%Web%'
l
Instead of table we use name of Java class
l
We assign alias to the entity to reference it
l
We may return both primitive types and complete
entities (by the reference)
l
We may compare entities (their id will be compared)
l
We may access fields and make joins by dot notation
23. JPQL – named queries
●Queries tied with a JPA entity using @NamedQuery
annotation
●Compiled and checked at application deployment
●Executed by a name
●Name of a named query must be unique in the whole
persistence unit, not only within the entity
24. JPQL – joins
●Joins are created when dot notation is used:
l
SELECT b.tags FROM Book b WHERE b.id = 2
●When we need to reference properties of the joined
entities, we must explicitely join them:
l
SELECT DISTINCT t.name FROM Book b INNER
JOIN b.tags t
l
Only mapped properties can be joined
25. Criteria API
●Criteria queries are written using Java APIs, are
typesafe, and are portable
●However, too much of complex code needs for even
simple queries
●Libraries exist to simplify working with criteria
●Criteria API is convenient to build dynamic queries
based on parameters (for search dialogs, filters, ...)
26. Lazy loading
● Simple types are loaded from DB at the time when entity is loaded
(EAGER)
● Collections are loaded only when a method on a collection is
executed (LAZY)
l
Only reference to a proxy collection is injected to the entity
● This behavior can be changed by FetchType attribute on collection
annotations
● When lazy collection is accessed when entity was disconnected from
transaction, LazyLoadingException is thrown
27. Lazy loading behavior
●Default fetch behavior can be changed by
FetchType attribute on collection annotations
●Lazy references can be loaded eagerly in
JPQL by fetch join
28. Lazy loading problems
●When lazy collection is accessed when entity
was disconnected from transaction,
LazyLoadingException is thrown
●There are various strategies to avoid this:
l
Data Transfer Objects, Extended Persistence
Context, ...
29. Id generation for primary key
●an attribute of type long or String is marked with @Id
●Strategies to generate Id values:
l
IDENTITY – id generation by the DB
l
SEQUENCE – generation of id from a sequence
l
TABLE – emulates SEQUENCE using a table
l
AUTO – JPA provider will choose according to what
is supported by the DB
30. Optimistic locking
●Technique to prevent conflicts without using DB
locking mechanism
l
DB locks are often too restrictive, slow down the
DB, may cause deadlocks
●Each row of a table stores its version number
●When JPA finds out that the transaction is trying to
modify an entity with older version than in DB, it
detects conflict and throws an exception with rollback
31. Optimistic locking – version attribute
●@Version marks entity property, which is mapped to
the version column
●Version number is updated and used by JPA
automatically