Corporate Profile 2014

Download Report

Transcript Corporate Profile 2014

Java Persistence API
Maciej Adamiak
Agenda
- Entity,
- Entity Operations,
- Query Language
ORM
Persistence
provider
POJO
Persistence
storage
Persistence
provider
HTML/JS
…
Spring
…
JPA
Storage / Database
JSF
EJB
Persistence Layer
JSP
Business Logic Layer
Presentation Layer
JPA in an enterprise class application
Oracle DB,
MySQL,
H2,
…
Providers
…
DataNucleus
Hibernate
EclipseLink
OpenJPA
JPA
Entity
EntityManager
EntityManagerFactory
Persistence Context
Metamodel
EntityManagerFactory
Example
Definition
EntityManagerFactory interface is
used by the application to obtain
an application - managed entity
manager.
When the application has finished
using the entity manager factory,
and/or at application shutdown,
the application should close the
entity manager factory. Once an
entity manager factory has been
closed, all its entity managers are
considered to be in the closed
state.
Exercise I - Configuration
Create a new Maven project or create a JPA project (advanced)
Add dependencies:
• hibernate-entitymanager,
• h2 or mysql connector (advanced),
Create src/main/resources/META-INF/persistence.xml file
• Define the persistance-unit as UL_JPA
• Provider: org.hibernate.ejb.HibernatePersistence
• Properties:
• hibernate.connection.url=jdbc:h2:./JpaExampleDB
• hibernate.dialect=org.hibernate.dialect.H2Dialect
• hibernate.connection.driver_class=org.h2.Driver
Create an EntityManager in main to test your configuration
• EntityManagerFactory emf = Persistence.createEntityManagerFactory("UL_JPA");
Entity
An entity is a lightweight persistent domain object.
The primary programming artifact is the entity class. An entity class may
make use of auxiliary classes that serve as helper classes or that are used
to represent the state of the entity.
The entity class is a top-level non-final class. An enum or interface must
not be designated as an entity. The entity class must be annotated with
the Entity annotation or denoted in the XML descriptor as an entity.
The entity class must have a no-arg constructor. The entity class may have
other constructors as well.
The persistent state of an entity is represented by instance variables,
which may correspond to Java-Beans properties
Common Entity Annotations
@Id
•The Id annotation specifies the primary key property or field of an entity. The Id annotation may be applied in an entity or mapped superclass.
•The field or property to which the Id annotation is applied should be one of the following types: any Java primitive type; any primitive wrapper
type; java.lang.String; java.util.Date; java.sql.Date; java.math.BigDecimal; java.math.BigInteger.
@Column
•The Column annotation is used to specify a mapped column for a persistent property or field
@OneToOne, @OneToMany, @ManyToOne, @ManyToMany
•The ...To... annotations define a single/multiple-valued association to another entity that has ...-to-... multiplicity. It is not normally necessary
to specify the associated target entity explicitly since it can usually be inferred from the type of the object being referenced.
•If the relationship is bidirectional, the mappedBy element must be used to specify the relationship field or property of the entity that is the
owner of the relationship.
@Inheritance
•The Inheritance annotation defines the inheritance strategy to be used for an entity class hierarchy.
•It is specified on the entity class that is the root of the entity class hierarchy.
@JoinColumn
•The JoinColumn annotation is used to specify a column for joining an entity association or element collection.
•The name annotation element defines the name of the foreign key column. The remaining annotation elements (other than
referencedColumnName) refer to this column and have the same semantics as for the Column annotation
Exercise II – creating a domain model
Layer
•
•
•
•
POI,
AltitudePoint,
PathNode
Car
Polygon (Area)
• UrbanArea,
• GreenArea
• ...
Line
View
EntityManager
Definition
An
EntityManager
instance
is
associated with a persistence context.
A persistence context is a set of entity
instances in which for any persistent
entity identity there is a unique entity
instance. Within the persistence
context, the entity instances and their
lifecycle are managed.
The EntityManager interface defines
the methods that are used to interact
with the persistence context. The
EntityManager API is used to create
and
remove
persistent
entity
instances, to find persistent entities by
primary key, and to query over
persistent entities.
The set of entities that can be
managed by a given EntityManager
instance is defined by a persistence
unit. A persistence unit defines the set
of all classes that are related or
grouped by the application, and which
must be colocated in their mapping to
a single database.
Example
Transaction
Definition
Depending on the transactional type of the entity manager,
transactions involving EntityManager operations may be controlled
either through JTA or through use of the resource-local
EntityTransaction API, which is mapped to a resource transaction
over the resource that underlies the entities managed by the entity
manager.
An entity manager whose underlying transactions are controlled
through JTA is termed a JTA entity manager. An entity manager
whose underlying transactions are controlled by the application
through the EntityTransaction API is termed a resource-local entity
manager.
A container-managed entity manager must be a JTA entity manager.
JTA entity managers are only specified for use in Java EE containers.
An application-managed entity manager may be either a JTA entity
manager or a resource-local entity manager.
An entity manager is defined to be of a given transactional type—
either JTA or resource-local—at the time its underlying entity
manager factory is configured and created.
Both JTA entity managers and resource-local entity managers are
required to be supported in Java EE web containers and EJB
containers. Within an EJB environment, a JTA entity manager is
typically used. In general, in Java SE environments only resource-local
entity managers are supported.
Example
Entity operations
void persist(Object entity);
<T> T merge(T entity);
void remove(Object entity);
•Make an instance managed and persistent.
•Merge the state of the given entity into the
current persistence context.
•Remove the entity instance.
<T> T find(Class<T> entityClass, Object
primaryKey);
<T> T getReference(Class<T>
entityClass, Object primaryKey);
Query createQuery(String qlString);
•Find by primary key.
•Search for an entity of the specified class and
primary key. If the entity instance is contained in
the persistence context it is returned from there.
•Get an instance, whose state may be lazily
fetched.
•The application should not expect that the
instance state will be available upon
detachment, unless it was accessed by the
application while the entity manager was open.
•Create an instance of Query for executing a Java
Persistence query language statement.
Exercise III – entity operations
Persist a Point in the DB
Find a persisted Point
Update found Point
Delete updated Point
MetaModel / Canonical Metamodel
Definition
Java Persistence criteria queries are based on a metamodel of the
managed classes of the persistence unit. Static metamodel classes
corresponding to the managed classes of the persistence unit can be
generated by means of an annotation processor or can be created by
the application developer, or the metamodelcan be accessed
dynamically by use of thejavax.persistence.metamodel.Metamodel
interface. The getMetamodel method of the EntityManagerFactory or
EntityManager interface can be used to obtain a Metamodel instance.
For each managed class X in package p, a metamodel class X_ in
package p is created. The name of the metamodel class is derived from
the name of the managed class by appending "_" to the name of the
managed class. The metamodel class X_ must be annotated with the
javax.persistence.Static- Metamodel annotation.
If class X extends another class S, where S is the most derived managed
class (i.e., entity or mapped superclass) extended by X, then class X_
must extend class S_, where S_ is the metamodel class created for S.
For every persistent non-collection and collection-valued attribute y
declared by class X, where the type of y is Y, the metamodel class must
contain a declaration.
Example
JPQL I
The Java Persistence query language is a query specification
language for string-based dynamic queries and static queries
expressed through metadata. It is used to define queries over the
persistent entities defined by this specification and their persistent
state and relationships.
The Java Persistence query language can be compiled to a target
language, such as SQL, of a database or other persistent store. This
allows the execution of queries to be shifted to the native language
facilities provided by the database, instead of requiring queries to be
executed on the runtime representation of the entity state. As a
result, query methods can be optimizable as well as portable.
The query language uses the abstract persistence schema of entities,
including their embedded objects and relationships, for its data
model, and it defines operators and expressions based on this data
model. It uses a SQL-like syntax to select objects or values based on
abstract schema types and relationships. It is possible to parse and
validate queries before entities are deployed.
JPQL II
Path
variable
In BNF:
select_statement :: = select_clause
from_clause [where_clause]
[groupby_clause]
[having_clause] [orderby_clause]
@Entity
JPQL
Task
SELECT e FROM Employee e
Select all employee entities
SELECT li from Order o inner join
o.lineItems li
SELECT li from Order o IN(o.lineItems) li
Get all orders lineitems
SELECT c FROM Customer c LEFT OUTER
JOIN FETCH c.orders
Select all customers and fetch their orders.
If Collection<Order> in Customer has been
marked @Lazy
select s from Student s where s.score =
(select max(s1.score) from Student s1)
Return the Student having highest score
Criteria API
Definition
The javax.persistence.criteria API interfaces are
designed both to allow criteria queries to be
constructed in a strongly-typed manner, using
metamodel objects to provide type safety, and to
allow or string-based use as an alternative.
A CriteriaQuery object is created by means of one of the
createQuery methods or the createTupleQuery method
of the CriteriaBuilder interface. A CriteriaQuery object is
typed according to its expected result type when the
CriteriaQuery object is created. A TypedQuery instance
created from the CriteriaQuery object by means of the
EntityManager createQuery method will result in
instances of this type when the resulting query is
executed.
The following methods are provided for the
creation of CriteriaQuery objects:
•<T> CriteriaQuery<T> createQuery(Class<T>
resultClass);
•CriteriaQuery<Tuple> createTupleQuery();
•CriteriaQuery<Object> createQuery();
Example
Exercise III – entity operations
Create a list of more than 100 Points
Persist the list using the EntityManager
Find all points that have x > 10 and y < 50
• A. Use em.getResultList() to get the query result.
• B. Use em.getSingleResult() to get the query result.
Final Exercise
Create a console application.
• Give the user a possibility to manage different types of map/plan elements
• Create, Delete, Remove, Update and compose them in layers.
• Use JPA to persist data.
• Add a command to display the report content of each created layer.
• Tips:
• Use Apache CLI or a Scanner object to create a console application,
• Use Factory design pattern to create object from console parameters,
• Use Command design pattern to create CRUD operations.
• Use DAO pattern for persistence.
Bibliography
Pro JPA 2; Mike Keith, Merrick Schincariol
Head First: Design Patterns; Eric Freeman, Elisabeth Freeman
JSR 317: JavaTM Persistence API, Version 2.1
www.tt.com.pl