650 likes | 910 Views
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
E N D
EclipseLink JPABlack 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 • Management & Diagnostics • Customizations • Tuning
Spring ADF EclipseLink Project Java SE Java EE OSGi EclipseLink JPA MOXy EIS SDO DBWS XML Data Legacy Systems Databases
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
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
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
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
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; } …}
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; } …}
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; } …}
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
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
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
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
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
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
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
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(); } }
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
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
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;
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
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
Default Mappings ADDRESS POSTALCODE ID CITY COUNTRY
Overriding Default Mappings ADDRESS P_CODE ID CITY COUNTRY
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)
@Entity @Id @ManyToOne ManyToOne Mapping public class Customer { int id; Address addr; } CUSTOMER ADDRESS ID ADDR_ID ID . . .
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 . . .
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
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
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
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
Object Model public abstract class Animal { int id; String name; public class LandAnimal extends Animal { int legCount; } public class AirAnimal extends Animal { short wingSpan; }
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
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; }
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; }
Application Bootstrap for EM public class JavaServiceFacade { private EntityManagerFactory emf = Persistence.createEntityManagerFactory("Project3"); private EntityManager getEntityManager() { return emf.createEntityManager(); }
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()
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); }
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
EclipseLink Native Meta Model DatabasePlatform Session Project (Map) ServerPlatform * ClassDescriptor Class javaClass Policies InstantiationClone/CopyInheritanceLockingSequencing… * Mapping attributeName
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
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
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
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
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)
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();
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();
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
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 */