1 / 65

EclipseLink JPA Black Belt Course

EclipseLink JPA Black Belt Course. Section 1: Introduction <PRESENTER>. Eclipse JPA – Black Belt Introduction. Goal Provide deeper understanding of EclipseLink JPA Topics JPA in a Nutshell Native model and API EclipseLink JPA extension points Mapping Querying Caching Transactions

ardara
Download Presentation

EclipseLink JPA Black Belt Course

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. EclipseLink JPABlack Belt Course Section 1: Introduction <PRESENTER>

  2. Eclipse JPA – Black Belt Introduction • Goal • Provide deeper understanding of EclipseLink JPA • Topics • JPA in a Nutshell • Native model and API • EclipseLink JPA extension points • Mapping • Querying • Caching • Transactions • Management & Diagnostics • Customizations • Tuning

  3. Spring ADF EclipseLink Project Java SE Java EE OSGi EclipseLink JPA MOXy EIS SDO DBWS XML Data Legacy Systems Databases

  4. EclipseLink: Distributions • Eclipse.org • www.eclipse.org/eclipselink/downloads • http://download.eclipse.org/rt/eclipselink/updates • Oracle • TopLink 11g • WebLogic Server 10.3 • GlassFish v3 • Replaces TopLink Essentials • JPA 2.0 Reference Implementation • Spring Source • Spring Framework • Spring OSGi Bundle Repository • JOnAS Application Server 5.1

  5. EclipseLink Developer Tool Support • EclipseLink is a Runtime Project but supported by IDEs • Eclipse IDE • EclipseLink support included by Dali in Eclipse 3.4 (Ganymede) • EclipseLink included in Eclipse 3.5 (Galileo) – JavaEE • Enhanced Dali support for use of EclipseLink • Oracle Enterprise Pack for Eclipse (OEPE) • MyEclipse • JDeveloper 11g • JPA, Native ORM, OXM, and EIS mapping • NetBeans • Standalone Workbench • Native ORM, OXM, EIS

  6. JPA 1.0 in a Nutshell • Entities • POJOs: No interfaces or parent classes • Zero Argument Constructor • Serializable (optional) • Configuration • /META-INF/persistence.xml • JTA or RESOURCE_LOCAL • data source or native connection pooling • Mappings: Annotations and/or XML • API • EntityManager & EntityManagerFactory • Query with JP QL or Native SQL • EntityTransaction • @PersistenceContext, @PersistenceUnit

  7. What is a JPA Entity? • Entity == Plain Old Java Object (POJO) + Mapping Netadata • Specified by @Entity or through XML config • Identity: @Id or @IdClass (composite PK) • Mapping Metadata • Annotations • Can be specified on attribute or on getter methods • ORM XML • Defaults

  8. Entity: POJO @Entity@Table(name=“EMPLOYEE”)public class Employee {@Id @Column(name=“EMP_ID”) private long id; @Basic @Column(name=“NAME”) private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } …}

  9. Entity Mapping using Annotations @Entity@Table(name=“EMPLOYEE”)public class Employee {@Id @Column(name=“EMP_ID”) private long id; @Basic @Column(name=“NAME”) private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } …}

  10. Entity: Configuration by Exception @Entity@Table(name=“EMPLOYEE”)public class Employee {@Id @Column(name=“EMP_ID”) private long id; @Basic @Column(name=“NAME”) private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } …}

  11. Entity Mapping using ORM XML • Annotations and/or XML can be used <entity class=“model.Employee”> <attributes> <id name=“id”> <column name=“EMP_ID”/> </id> </attributes> </entity> • XML can also be used to override/customize annotations

  12. Operations on Entities • EntityManager (javax.persistence) • persist()- Insert the identity of an entity into the db • remove()- Delete the persistent identity of the entity from the db • refresh()- Reload the entity state from the db • merge()- Synchronize the state of detached entity with the pc • find()- Execute a simple PK query • createQuery()- Create query instance using JP QL • createNamedQuery()- Create instance for a predefined query • createNativeQuery()-Create instance for an SQL query • contains()- Determine if entity is managed by pc • flush()- Force synchronization of pc to database

  13. public Order createNewOrder(Customer customer) { Order order = new Order(customer); entityManager.persist(order); return order; } Persist Operation • Can only pass new or managed instances to persist() • Exception thrown if object was detached • Exception may be thrown immediately or at commit time

  14. Find and Remove Operation public void removeOrder(Long orderId) { Order order = entityManager.find(Order.class, orderId); entityManager.remove(order); } • Can only pass managed instances to remove() • Exception thrown if object was detached • Detached instances must first be merged, or managed instances with same persistence identity must be obtained

  15. Merge Operation public OrderLine updateOrderLine(OrderLine orderLine) { return entityManager.merge(orderLine); } • Detached instances become managed • Detached state merged into the persistence context • Merge returns managed instance with the same persistent identity but with different Java object identity • Managed objects ignored

  16. Entity Callbacks • An EntityListener may be associated with certain defined entity lifecycle events • PrePersist—when the application calls persist() • PostPersist—after the SQL INSERT • PreRemove—when the application calls remove() • PostRemove—after the SQL DELETE • PreUpdate—when the container detects that an instance is dirty • PostUpdate—after the SQL UPDATE • PostLoad—after an instance was loaded

  17. Queries • Dynamic or statically defined and named • Specified using JP QL • Native SQL support (when required) • Named parameters bound at execution time • Pagination and ability to restrict size of result • Single / multiple-entity results, data projections • Bulk update and delete operation on an entity • Standard hooks for vendor-specific hints

  18. Dynamic Queries public class CustomerQueries { EntityManager em = getEntityManager(); … public List findCustByName (String name) { return em.createQuery ( “SELECT c FROM Customer c ” + “WHERE c.name LIKE :custName”) .setParameter(“custName”, name) .setMaxResults(10) .getResultList(); } }

  19. Named Queries @NamedQuery(name=“findCustomersByName”, query=“SELECT c FROM Customer c WHERE c.name LIKE :custName”) @Entity public class Customer { … } public List findCustByName (String name) { return em.createNamedQuery(“findCustomersByName”) .setParameter(“custName”, name) .setMaxResults(10) .getResultList(); } Note: Parameters can also be specified using position

  20. Object/Relational Mapping • Specified as annotations or XML • Logical and physical mapping configuration • Logical—object model (e.g. @OneToMany) • Physical—DB tables and columns (e.g. @Table) • Support for basic, serialized objects, enums, LOBs, etc. • Unary, n-ary relationship mappings • Rules for defaulting of DB table and column names • Access to object state using fields or properties • Multiple tables, composite relationship keys

  21. Identity: Primary Keys • Id field required in the domain entity • Can be a simple field using @Id • @Id int custId; • Composite primary keys require • @IdClass(CustPK.class) • Use @EmbeddedId to indicate a single id field to store an instance of a composite PK class • @EmbeddedId CustPK id;

  22. Fetching and Cascading • Fetch mode is a hint to the Container to defer loading specific fields or relationships until they are accessed • Can specify EAGER or LAZY loading • Specified as metadata on the mappings • Cascading of entity operations to related entities • Can cascade PERSIST, MERGE, REMOVE, REFRESH, ALL • Setting may be defined per-relationship or for all relationships • Applied when corresponding EntityManager API used

  23. Simple Mappings • Direct mapping of simple Java field to standard DB column type using @Basic • Is default mapping type assumed by non-annotated fields • May be used in conjunction with @Column (physical mapping annotation) • May be augmented • @Lob • @Enumeration • @Temporal • Defaults to the type deemed most appropriate if no mapping annotation is present • Can override any of the defaults

  24. Default Mappings ADDRESS POSTALCODE ID CITY COUNTRY

  25. Overriding Default Mappings ADDRESS P_CODE ID CITY COUNTRY

  26. Relationship Mappings • Common relationship mappings supported • @ManyToOne, @OneToOne - single entity • @OneToMany, @ManyToMany - collection of entities • Unidirectional or bidirectional • Owning and inverse sides, owning side specifies the physical mapping • @JoinColumn to specify foreign key column • @JoinTable for decoupling relationship from source entity (e.g. ManyToMany)

  27. @Entity @Id @ManyToOne ManyToOne Mapping public class Customer { int id; Address addr; } CUSTOMER ADDRESS ID ADDR_ID ID . . .

  28. OneToMany Mapping public class Order { int id; ... Customer cust; } public class Customer { int id; ... Set<Order> orders; } @Entity @Entity @Id @Id @OneToMany(mappedBy=“cust”) @ManyToOne ORDER CUSTOMER ID CUST_ID . . . ID . . .

  29. ManyToMany Mapping public class Phone { int id; ... Collection<Customer> custs; } public class Customer { int id; ... Collection<Phone> phones; } @Entity @Entity @Id @Id @ManyToMany(mappedBy=“phones”) @ManyToMany PHONE CUSTOMER ID . . . ID . . . CUSTOMER_PHONE CUSTS_ID PHONES_ID

  30. ManyToMany Mapping @Entity public class Customer { ... @ManyToMany @JoinTable(table=@Table(name=“CUST_PHONE”), joinColumns=@JoinColumn(name=“CUST_ID”), inverseJoinColumns=@JoinColumn(name=“PHON_ID”)) Collection<Phone> phones; } PHONE CUSTOMER ID . . . ID . . . CUST_PHONE CUST_ID PHON_ID

  31. Mapping Embedded Objects public class Customer { int id; CustomerInfo info;} public class CustomerInfo { String name; int credit; Image photo; } @Entity @Embeddable @Id @Embedded CUSTOMER PHOTO ID NAME CREDIT

  32. Inheritance • Entities can extend • Other entities — concrete or abstract • Non-entity classes — concrete or abstract • Map inheritance hierarchies in three ways • Single table — all classes stored in the same table • Joined — Each class (concrete or abstract) stored in a separate table • Table per concrete class — Each concrete class stored in separate table (optional) • Mapped Superclass • Define common mappings • Not Object-Relational Inheritance

  33. Object Model public abstract class Animal { int id; String name; public class LandAnimal extends Animal { int legCount; } public class AirAnimal extends Animal { short wingSpan; }

  34. Single table: Data Models ANIMAL ID DISC NAME LEG_CNT WING_SPAN ANIMAL ID NAME • Joined: LAND_ANML AIR_ANML ID LEG_COUNT ID WING_SPAN LAND_ANML AIR_ANML • Table per Class: ID NAME LEG_COUNT ID NAME WING_SPAN

  35. Entity Manager Injection @Stateless public class EmployeeDemoSessionEJB implements EmployeeDemoSession { // Field Injection @PersistenceContext(unitName=“default”) protected EntityManager em; OR // Setter Injection @PersistenceContext(unitName=“default”) public void setEntityManger(EntityManager em){ this.em = em; }

  36. Entity Manager JNDI Lookup @Stateless public class EmployeeDemoSessionEJB implements EmployeeDemoSession { protected EntityManager em; public EntityManager getEntityManager() { if (em == null} { try { em = (EntityManager)(newInitialContext()). lookup("java:comp/ejb/EntityManager"); } catch (Exception e){}; } return em; }

  37. Application Bootstrap for EM public class JavaServiceFacade { private EntityManagerFactory emf = Persistence.createEntityManagerFactory("Project3"); private EntityManager getEntityManager() { return emf.createEntityManager(); }

  38. Application Managed Transaction • javax.persistence.EntityTransaction • EntityManager.getTransaction() • Allows application managed TX control • Throws an exception in container managed • EntityTransaction API • begin() • commit() • rollback() • isActive()

  39. Simple Container Managed Transaction @Stateless public class EmployeeDemoSessionEJB implements EmployeeDemoSession { ... public void createEmployee(String fName, String lName) { Employee employee = new Employee(); employee.setFirstName(fName); employee.setLastName(lName); em.persist(employee); } public void removeEmployee(Integer id) { Employee employee = (Employee)em.find("Employee", id); ... em.remove(employee); }

  40. Most Used Extensions to JPA • Persistence Unit Properties • Direct JDBC usage and pooling • Logging • Database and Server Platform • Cache Configuration • Schema generation • Query Hints • Joining, Batching • Cache Usage • Lazy Fetch • OneToOne and ManyToOne • Basic – Fetch Groups

  41. EclipseLink Native Meta Model DatabasePlatform Session Project (Map) ServerPlatform * ClassDescriptor Class javaClass Policies InstantiationClone/CopyInheritanceLockingSequencing… * Mapping attributeName

  42. Role of Session • Java application’s primary interface to EclipseLink and the relational database. • EclipseLink services are invoked through the session. Java Application (objects) JPA EntityManager EclipseLink Session JDBC JDBC SQL rows

  43. Session API • oracle.eclipselink.sessions.Session • Interface implemented by all sessions • Primary interface used in application code • Features • Query execution • Transaction access - UnitOfWork • Cache access and control (IdentityMapAccessor) • Diagnostics: Logging & profiling • Lifecycle • Customization - events

  44. Session Types • Database session • Used for 2-tier/client-server applications • Single JDBC connection • Direct object modification calls and TX control • Server session • Concurrent multi-client/thread • Shared cache and connection pooling capabilities • Object changes permitted only through UnitOfWork • UnitOfWork • Transaction API

  45. Additional Session Types • Session broker • Connect to multiple session as one • Support for multiple independent databases • Remote session • Client-side sessions providing access to EclipseLink services via the Server session on a server • Not commonly used • Note: will be deprecated in future release

  46. Session Configuration • Stored in deployment XML file or Java class • Direct use of Project • Read XML (XMLProjectReader) • Java class: instantiate new project instance • Sessions.xml (Recommended) • SessionManager Manages Singleton Session: Server, Database, or Broker • SessionFactory Helper to simplify application access Used in Generated Session Beans (JDeveloper)

  47. Creating a Project from Map XML • Two options: • Read the deployable XML project file that is generated through the Workbench. • Create an instance of the Project class that is generated through the Workbench. import oracle.eclipselink.sessions.*; import oracle.eclipselink.tools.workbench.*; … Project project = XMLProjectReader.read(“/META-INF/Employee.XML”); import oracle.eclipselink.sessions.*; import packagename.EmployeeProject; … EmployeeProject project = new EmployeeProject();

  48. Creating a Session • Use the project to create a session: import oracle.eclipselink.sessions.DatabaseSession; import oracle.eclipselink.sessions.Project; import oracle.eclipselink.tools.workbench.*; Project project = XMLProjectReader.read(“/META-INF/Employee.XML”); DatabaseSession session=project.createDatabaseSession(); session.login();

  49. SessionManager • Package: • oracle.eclipselink.tools.sessionmanagement • Purpose: • Provides a singleton instance of a session manager which can access named sessions • Supports three session types • DatabaseSession • ServerSession • SessionBroker

  50. SessionManager • SessionManager.getManager() /* returns a singleton instance of the SessionManager */ sessionManager.getSession(String sessionName) /* Default behavior, will load named session from the sessions.xml file in the classpath root directory. Will load a session from the singleton if one already exists */

More Related