ORM Concepts and JPA 2.0 Specifications
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

ORM Concepts and JPA 2.0 Specifications

on

  • 497 views

Brief and solid explaination for ORM concepts and JPA 2 .0 specifications .

Brief and solid explaination for ORM concepts and JPA 2 .0 specifications .

Statistics

Views

Total Views
497
Views on SlideShare
497
Embed Views
0

Actions

Likes
1
Downloads
21
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • https://forums.oracle.com/forums/thread.jspa?threadID=673888

ORM Concepts and JPA 2.0 Specifications Presentation Transcript

  • 1. Object Relational Mapping (ORM) ahmed.s.ramzy@gmail.com 1
  • 2. 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 ahmed.s.ramzy@gmail.com 2
  • 3. 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. ahmed.s.ramzy@gmail.com 3
  • 4. 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. ahmed.s.ramzy@gmail.com 4
  • 5. 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. ahmed.s.ramzy@gmail.com 5
  • 6. 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. ahmed.s.ramzy@gmail.com 6
  • 7. 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). ahmed.s.ramzy@gmail.com 7
  • 8. 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. ahmed.s.ramzy@gmail.com 8
  • 9. Entities (cont.) ahmed.s.ramzy@gmail.com 9
  • 10. 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. ahmed.s.ramzy@gmail.com 10
  • 11. persistence.xml ahmed.s.ramzy@gmail.com 11
  • 12. 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 ahmed.s.ramzy@gmail.com 12
  • 13. Relationship Mapping (cont.) OneToOne Example ahmed.s.ramzy@gmail.com 13
  • 14. Inheritance Mapping Consider the following Inheritance hierarchy ahmed.s.ramzy@gmail.com 14
  • 15. 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. ahmed.s.ramzy@gmail.com 15
  • 16. 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. ahmed.s.ramzy@gmail.com 16
  • 17. 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). ahmed.s.ramzy@gmail.com 17
  • 18. 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. ahmed.s.ramzy@gmail.com 18
  • 19. 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. ahmed.s.ramzy@gmail.com 19
  • 20. 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(); ahmed.s.ramzy@gmail.com 20
  • 21. 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 query Query query = em.createNamedQuery(" findCityCustomers "); query.setParameter("city ", “Cairo"); List<Customer> customers = query.getResultList(); • Can be more efficient to execute. ahmed.s.ramzy@gmail.com 21
  • 22. 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 ") ahmed.s.ramzy@gmail.com 22
  • 23. 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")); ahmed.s.ramzy@gmail.com 23
  • 24. Callbacks ahmed.s.ramzy@gmail.com 24
  • 25. 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"); } ahmed.s.ramzy@gmail.com 25
  • 26. 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. ahmed.s.ramzy@gmail.com 26
  • 27. 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. ahmed.s.ramzy@gmail.com 27
  • 28. 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 { ……….} ahmed.s.ramzy@gmail.com 28
  • 29. 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. ahmed.s.ramzy@gmail.com 29
  • 30. 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. ahmed.s.ramzy@gmail.com 30
  • 31. ahmed.s.ramzy@gmail.com 31