Download - ORM Concepts and JPA 2.0 Specifications
Object Relational Mapping (ORM)
ahm
ed.s
.ram
zy@
gmai
l.com
1
Summary• ORM Principle and brief history.• Persistence Products.• Oracle TopLink.• From TopLink to EclipseLink.• EclipseLink:• Entities• Entity Manager• persistence.xml• Relationship Mapping• Inheritance Mapping• Queries• Callbacks• Listeners• Concurrency• Caching
ahm
ed.s
.ram
zy@
gmai
l.com
2
Object Relational Mapping (ORM)• The principle of ORM involves delegating access to relational
databases to external tools or frameworks.• Mapping tools give an object-oriented view of relational data,
and vice versa.• Container Managed Persistence (CMP) was introduced in EJB
1.0 as the persistence model of J2EE 1.2.• Hibernate framework gave a lightweight, object-oriented
persistent model.• JPA was defined as part of the EJB 3.0 specification as a
replacement for the EJB 2 CMP• JPA is now considered the standard industry approach for
Object to Relational Mapping (ORM) in the Java Industry.
ahm
ed.s
.ram
zy@
gmai
l.com
3
ORM (cont.)
• JPA itself is just a specification, it only describes persistence concepts and provides standard interfaces.
• Any Java EE 5 (and above) application server should provide support for its use.
• The latest JPA specification version is JPA 2.1 .• There are open-source and commercial JPA implementations:• Hibernate (acquired by JBoss, acquired by Red Hat),• TopLink (Oracle),• OpenJPA (Apache project),• EclipseLink (Eclipse Foundation project).
• EclipseLink was announced to be the JPA 2.0 reference implementation.
ahm
ed.s
.ram
zy@
gmai
l.com
4
ORM (cont.)
• Most persistence products now support a JPA interface.• Most people would recommend you use the JPA standard
whichever product you choose.• This gives you the flexibility to switch persistence providers.• To determine which persistence product to use consider these
questions:• Which persistence product does your server platform support?• Is the product active and does it have a large user base?• How does the product perform and scale?• Does the product good documented and have active and open
forums?• What functionality does the product offer beyond the JPA
specification?• Use the reference implementation where you can, other
where you must.
ahm
ed.s
.ram
zy@
gmai
l.com
5
TopLink & EclipseLink• TopLink is the Oracle persistence provider solution.
• In 2007, TopLink 11g source code was donated to the Eclipse Foundation and the EclipseLink project was born.
• In 2008 Sun Microsystems selected the EclipseLink project as the reference implementation for the JPA 2.0 specification.
• Oracle default JPA solution will be delivered through the EclipseLink implementations.
ahm
ed.s
.ram
zy@
gmai
l.com
6
Entities• Object that maps to relational database table will be called Entity and
once mapped it can be managed by JPA .
• JPA map entities to a database through metadata using two formats:• Annotations: the entity class is directly annotated with annotations.• XML descriptors: The mapping is defined in an external XML file.
• JPA uses the concept of configuration by exception (programming by exception).
• The entity name is mapped to a relational table name.
• Attribute names are mapped to a column name.
• Entity must define a primary key (single field or a combination of fields).
ahm
ed.s
.ram
zy@
gmai
l.com
7
Entities (cont.)
• The default mapping rules are different from one database to another.
• It’s possible to map a single entity to several tables.
• Operations can be made on entities are persisting, updating, removing, and loading.
• Each operation has a “Pre” and “Post” event (except for loading, which only has a “Post” event).
• Entities are just POJOs when they managed by Entity Manager their state is synchronized with the database .
• when entities detached from the entity manager they can be used like any other Java class.
ahm
ed.s
.ram
zy@
gmai
l.com
8
Entities (cont.)
ahm
ed.s
.ram
zy@
gmai
l.com
9
Entity Manager• The central piece of the API responsible for orchestrating
entities is the entity manager.• Entity Manager is just an interface whose implementation is
done by the persistence provider, EclipseLink.• It allows simple CRUD operations as well as complex queries
using JPQL (Java Persistence Query Language).• Queries can be divided to:• dynamic queries (created dynamically at runtime), • static/named queries (defined statically at compile time), • native SQL statement.
• The persistence context describes all Entities of one Entity manager.
ahm
ed.s
.ram
zy@
gmai
l.com
10
persistence.xml
ahm
ed.s
.ram
zy@
gmai
l.com
11
Relationship Mapping• JPA allows to define relationships between classes (Entities).
• A relationship can be bidirectional or unidirectional.
• In a bidirectional relationship both classes store a reference to each other while in an unidirectional case only one class has a reference to the other class.
• Relationship annotations: • @OneToOne• @OneToMany• @ManyToOne• @ManyToMany
ahm
ed.s
.ram
zy@
gmai
l.com
12
Relationship Mapping (cont.)OneToOne Example
ahm
ed.s
.ram
zy@
gmai
l.com
13
Inheritance MappingConsider the following Inheritance hierarchy
ahm
ed.s
.ram
zy@
gmai
l.com
14
Inheritance Mapping (cont.)
• The root entity class can define the inheritance strategy by using the @Inheritance annotation.
• If it doesn’t, the default single-table-per-class hierarchy strategy will be applied.
• Inheritance Strategies :
• A single-table-per-class.
• A joined-subclass.
• A table-per-concrete-class.
ahm
ed.s
.ram
zy@
gmai
l.com
15
Inheritance Mapping (cont.)• A single-table-per-class hierarchy strategy: The sum of the
attributes of the entire entity hierarchy is flattened down to a single table (this is the default strategy). • A discriminator column used to differentiate between the entities.• adding new entities to the hierarchy, or adding attributes to existing
entities, involves adding new columns to the table, migrating data, and changing indexes.
• requires the columns of the child entities to be nullable.
ahm
ed.s
.ram
zy@
gmai
l.com
16
Inheritance Mapping (cont.)
• A joined-subclass strategy: each entity in the hierarchy is mapped to its own dedicated table.• A discriminator column used to differentiate between the entities.• The root entity maps to a table that defines the primary key to be
used by all tables in the hierarchy.• to reassemble an instance of a subclass, the subclass table has to be
joined with the root class table and the deeper the hierarchy, the more joins needed to assemble a leaf entity (impacts performance).
ahm
ed.s
.ram
zy@
gmai
l.com
17
Inheritance Mapping (cont.)
• A table-per-concrete-class strategy: This strategy maps each concrete entity hierarchy to its own separate table. • All attributes of the root entity will also be mapped to columns of the
child entity table. • the columns of the root class are duplicated on the leaf tables.• All tables must share a common primary key that matches across all
tables in the hierarchy.
ahm
ed.s
.ram
zy@
gmai
l.com
18
Queries• Supported query types:• Dynamic queries: consisting of a JPQL query string. • Named queries (static queries): static and unchangeable. • Native queries: to execute a native SQL statement.• Criteria API: object-oriented query API.
• Entity Manager has Methods for Creating Queries (or typed queries).
• Executing and controlling query made through the query interface APIs.
ahm
ed.s
.ram
zy@
gmai
l.com
19
JPQL• A query language that takes its roots in the syntax of SQL.• The main difference is that in JPQL the results obtained are
entity or a collection of entities.• Used to write dynamic queries: the query string may be
dynamically created at runtime.• JPQL syntax is object oriented .• Example:
Query query = em.createQuery("SELECT c FROM Customer c WHERE c.firstName=:fname"); query.setParameter("fname", "Ahmed");List<Customer> customers = query.getResultList();
ahm
ed.s
.ram
zy@
gmai
l.com
20
Named Queries• Defined by annotating an entity with the @NamedQuery
annotation.• Example: @NamedQuery
(name = "findCityCustomers",query="select c from Customer c where c.Address.city = :city);
To use this queryQuery query = em.createNamedQuery(" findCityCustomers ");
query.setParameter("city ", “Cairo");List<Customer> customers = query.getResultList();
• Can be more efficient to execute.
ahm
ed.s
.ram
zy@
gmai
l.com
21
Native Queries• The creator method takes a native SQL statement as the
parameter and return a Query instance .• Use the real database tables names.• the result can be automatically converted back to entities.• Example: Query query = em.createNativeQuery("SELECT * FROM
t_customer", Customer.class); List<Customer> customers = query.getResultList();
• Can use annotations to define static SQL queries.• Named, native queries defined using the
@NamedNativeQuery annotation on any entity. @NamedNativeQuery(name = "findAll", query="select *
from t_customer ")
ahm
ed.s
.ram
zy@
gmai
l.com
22
Criteria API• Supports everything JPQL can do but with an object-based
syntax.• The idea is that all the JPQL keywords (SELECT, WHERE, LIKE,
GROUP BY…) are defined in this API. • Supposed to help writing non error prone statements.• Example:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Customer> query = builder.createQuery(Customer.class);
Root<Customer> c = query.from(Customer.class); query.select(c).where(builder.equal(c.get("firstName"),
“Joe"));
ahm
ed.s
.ram
zy@
gmai
l.com
23
Callbacks
ahm
ed.s
.ram
zy@
gmai
l.com
24
Callbacks (cont.)
• Example:
@PrePersist
@PreUpdate private void validate() { if (firstName == null || "".equals(firstName)) throw new IllegalArgumentException("Invalid first
name"); if (lastName == null || "".equals(lastName)) throw new IllegalArgumentException("Invalid last
name"); }
ahm
ed.s
.ram
zy@
gmai
l.com
25
Callbacks (cont.)
• Callback Methods Rules:
• Can be public, private or protected but not static or final.
• May be annotated with multiple annotations but only one annotation of a given type may be present in an entity.
• Cannot invoke any Entity Manager or Query operations.
• With inheritance, if a method is specified on the superclass, it will get invoked before the method on the child class.
• A method can throw unchecked (runtime) exceptions but not checked exceptions.
ahm
ed.s
.ram
zy@
gmai
l.com
26
Listeners• Callback methods in an entity work well when you have business
logic that is only related to that entity.
• Entity listeners used to extract the business logic to a separate class and share it between other entities.
• An entity listener is just a POJO on which you can define one or more life-cycle callback methods.
• The entity needs to use the @EntityListeners annotation to register a listener.
ahm
ed.s
.ram
zy@
gmai
l.com
27
Listeners (cont.)
• Example:public class DataValidationListener { @PrePersist @PreUpdate private void validate(Customer customer) { if (customer.getFirstName() == null ||
"".equals(customer.getFirstName())) throw new IllegalArgumentException("Invalid first name");
if (customer.getLastName() == null || "".equals(customer.getLastName()))
throw new IllegalArgumentException("Invalid last name"); } }
In the entity class:@EntityListeners({DataValidationListener.class, ….}) @Entity public class Customer { ……….}
ahm
ed.s
.ram
zy@
gmai
l.com
28
Concurrency• locking can be achieved at the Entity Manager level and at the
Query level.
• Supported locking mechanisms are:• Optimistic locking :
• Permits all users to read and attempt to update the same data, concurrently.
• The decision to acquire a lock on the entity is actually made at the end of the transaction.
• Using entity Versioning allows the entity manager to automatically do optimistic locking on the entity.
• Pessimistic locking:• A lock is eagerly obtained on the entity before operating on it.• The database physically locks the row and only one user can update the
underlying data.• It is resource restrictive and results in significant performance
degradation.
ahm
ed.s
.ram
zy@
gmai
l.com
29
Caching• The entity manager is a first-level cache (not a performance cache).
• The second-level (performance) cache sits between the entity manager and the database to reduce database traffic.
• The @Cacheable annotation has attributes to control the caching process (e.g size,shared,expiry,type(Full,Weak,Soft …)).
• Caching mechanisms are: • ALL (the default)• DISABLE_SELECTIVE• ENABLE_SELECTIVE• NONE
• caching mechanism set at the persistence.xml file in the shared-cache-mode attribute.
ahm
ed.s
.ram
zy@
gmai
l.com
30
ahm
ed.s
.ram
zy@
gmai
l.com
31