EclipseLink JPA Introduction Course - Section 1: Introduction

aniseedsplashSoftware and s/w Development

Aug 15, 2012 (5 years and 4 days ago)

512 views

© 2002 IBM Corporation

Confidential | Date | Other Information, if necessary

March 16, 2013

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

Copyright ©2008 Oracle Corporation

Made available under the Eclipse Public License (EPL) v 1.0 and Eclipse Distribution License (EDL) v1.0

1

EclipseLink JPA Introduction Course

Section 1: Introduction

<PRESENTER>

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

2

Eclipse JPA Introduction


EclipseLink Project Overview


JPA in a Nutshell


EclipseLink JPA Topics


Native model and API


EclipseLink JPA extension points


Mapping


Querying


Caching


Transactions


Management & Diagnostics


Customizations


Tuning

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

3

EclipseLink Project



EclipseLink



DBWS



SDO



EIS



MOXy




JPA

XML Data

Legacy Systems

Databases

Java SE

Java EE

OSGi

Spring

ADF

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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


Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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; }






}

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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; }






}

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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; }






}

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

13

Persist Operation

public Order createNewOrder(Customer customer) {


Order order = new Order(customer);


entityManager.persist(order);


return order;

}


Can only pass new or managed instances to
persist()


Exception thrown if object was detached


Exception may be thrown immediately or at commit time

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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();

}

}

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

19

Named Queries

@NamedQuery(name=“Customer.findByName”,


query=“SELECT c FROM Customer c


WHERE c.name LIKE :custName”)

@Entity

public class Customer {




}

public List findCustByName (String name) {


return


em.createNamedQuery
(“Customer.findByName”)


.setParameter(
“custName”
, name)


.setMaxResults(10)


.getResultList();

}


Note: Parameters can also be specified using position


Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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;

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

24

Default Mappings

ADDRESS

ID

CITY

COUNTRY

POSTALCODE

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

25

Overriding Default Mappings

ADDRESS

ID

CITY

COUNTRY

P_CODE

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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)

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

27


public class Customer {



int id;



Address addr;

}


ManyToOne Mapping

CUSTOMER

ADDR_ID

ID

ADDRESS

. . .

ID

@Entity

@ManyToOne

@Id

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

28


public class Order {




int id;


...



Customer cust;

}



public class Customer {




int id;


...




Set<Order> orders;

}


OneToMany Mapping

@Entity

@Entity


@ManyToOne


@OneToMany(mappedBy=

cust

)

@Id

@Id

CUSTOMER

ID

. . .

ORDER

CUST_ID

ID

. . .

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

29


public class Phone {




int id;


...



Collection<Customer> custs;

}



public class Customer {




int id;


...



Collection<Phone> phones;

}


ManyToMany Mapping

PHONES_ID

CUSTS_ID

@Entity

@Entity

@Id

@Id

@ManyToMany

@ManyToMany(mappedBy=

phones

)

CUSTOMER

ID

. . .

PHONE

ID

. . .

CUSTOMER_PHONE

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

30

ManyToMany Mapping

PHON_ID

CUST_ID

CUSTOMER

ID

. . .

PHONE

ID

. . .

CUST_PHONE

@Entity

public class Customer {


...


@ManyToMany


@JoinTable(table=@Table(name=“CUST_PHONE”),


joinColumns=@JoinColumn(name=“CUST_ID”),


inverseJoinColumns=@JoinColumn(name=“PHON_ID”))


Collection<Phone> phones;

}

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

31


public class Customer {



int id;



CustomerInfo info;

}


public class CustomerInfo {


String name;


int credit;


Image photo;

}

Mapping Embedded Objects

CUSTOMER

ID

NAME

CREDIT

PHOTO

@Entity

@Embedded

@Id

@Embeddable

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

33

public class AirAnimal extends Animal {


short wingSpan;

}

Object Model

public abstract class Animal {


int id;


String name;

public class LandAnimal extends Animal {


int legCount;

}

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

34

Data Models

ANIMAL

LEG_CNT

ID

DISC

NAME

WING_SPAN


Single table:

ANIMAL

ID

NAME

LAND_ANML

ID

LEG_COUNT

AIR_ANML

ID

WING_SPAN


Joined:


Table per Class:

LAND_ANML

ID

LEG_COUNT

AIR_ANML

ID

WING_SPAN

NAME

NAME

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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;


}

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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;

}

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

37

Application Bootstrap for EM

public class JavaServiceFacade {



private EntityManagerFactory emf =



Persistence.createEntityManagerFactory("Project3");


private EntityManager getEntityManager() {


return emf.createEntityManager();

}


Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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()


Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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);

}

Copyright ©2010 Oracle Corporation

Made available under Creative Commons Attribution
-
Share Alike 3.0 Unported

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