en webinar jpa v2final

Download En webinar jpa v2final

If you can't read please download the document

Upload: alvaro-alcocer-sotil

Post on 10-May-2015

215 views

Category:

Documents


1 download

TRANSCRIPT

  • 1.Java Persistence APIEmil Nahlik (DC Bratislava)Copyright 2009 Accenture All Rights Reserved.

2. Centra ToolsRaise Hand Audio/Connectivity Tips Run the Audio WizardYes / No Choose Tools/Audio Wizard from the menu at top of screenApplause Close all network based applications Outlook, MSN/AOL, other websites, Office Communicator, etcLaugh Connect via an Accenture LAN or high speed internet connection If using a wireless connection, ensureText Chatyour signal is as strong as possible Monitor the Network ConnectivityCentra Volume ControlBar Contact Learning Product Support if issues continueNetwork Connectivity Bar 3. Asking QuestionsTwo Options:1. Ask live questions during the designated Q&A sessions: Press Raise Hand icon to get facultys attention Once called upon, there are two options to speak:- Click the Talk button or- Press the Ctrl key When done speaking, unselect the Talk button or release the Ctrl Key.2. Post questions at any time in the chat room. 4. Session structure Introduction Basic JPA Configuration Entity relationships Persistence operations and query language Transactions & optimistic/pessimistic locking DemoQ & ACopyright 2009 Accenture All Rights Reserved. 4 5. Introduction Java Persistence API (JPA) is a data persistence mechanism,that: is a part of JEE 5 (EJB3.0) works with Plain Old Java Objects (POJO) is DB-independent (configuration & JPA implementation) easy to use uses SQL-like language supports transactions and optimistic/pessimistic lockingCopyright 2009 Accenture All Rights Reserved. 5 6. IntroductionThere is no need to run an applicationserver to use JPA. It can run as a standalone, you need just a JPA implementationand properly configured XML file.Copyright 2009 Accenture All Rights Reserved. 6 7. Basic JPAConfiguration What does a typical JPA project consists of? JPA implementation Entities Entity manager Configuration file persistence.xmlCopyright 2009 Accenture All Rights Reserved. 7 8. JPA Implementation There are many JPA implementations: OpenJPA Hibernate TopLink CocoBase Castor JPOX etc.Copyright 2009 Accenture All Rights Reserved.8 9. Entities Entity represents domain object stored in DB is a POJO class is annotated as @Entity must implement Serializable interface must have declared ID attributeCopyright 2009 Accenture All Rights Reserved.9 10. Entities Example: @Entity public class Customer implements Serializable { private static final long serialVersionUID = 1L;@Idprivate Integer id;private String firstName;private String lastName; }Copyright 2009 Accenture All Rights Reserved. 10 11. Entities You can set ID (primary key) by your own @Entity public class Customer { @Id private int id = 0; } Somewhere in the code: Customer cust = new Customer(); cust.setId(123);Copyright 2009 Accenture All Rights Reserved.11 12. Entities Or you can use Sequence to generate ID (primary key) Sequence (in DB) Sequence genererator (in Entity) @Entity public class Customer { @Id @SequenceGenerator(name=Cust_Gen,sequenceName=Cust_Seq) @GeneratedValue(generator=Cust_Gen) private int id; }Copyright 2009 Accenture All Rights Reserved.12 13. Entity Manager Entity Manager is responsible for managing persistence and transactions. Create-Read-Update-Delete (CRUD) operations Java Persistence Query Language (JPQL) Access to transactionsCopyright 2009 Accenture All Rights Reserved. 13 14. Configuration file There is persistence.xml configuration file that contains JPA configuration. Inside this file, we define Persistence Unit and configure: JPA provider class Data source Transaction type (JTA / non-JTA) List of entity classes that are persisted by Persistence Unit Additional parameters e.g. Hibernate dialectCopyright 2009 Accenture All Rights Reserved.14 15. Configuration file org.hibernate.ejb.HibernatePersistenceTEST_DBjpa.webinar.entities.Personjpa.webinar.entities.Addressjpa.webinar.entities.PhoneNumberCopyright 2009 Accenture All Rights Reserved. 15 16. Entities andRelationships There are many types of relationships: 1-to-1 unidirectional (AB) / bidirectional (AB) 1-to-N unidirectional / bidirectional N-to-1 unidirectional / bidirectional M-to-N always bidirectionalCopyright 2009 Accenture All Rights Reserved. 16 17. Entities andRelationshipsUnidirectional relationship Bidirectional relationship1-to-1 (A B)1-to-N (A B)ClassA a = new ClassA();ClassA a = new ClassA();ClassB b = new ClassB();ClassB b = new ClassB();a.setB(b);a.addB(b);b.setA(a);For bidirectional relationships,we always have to set both sidesof relationship!Copyright 2009 Accenture All Rights Reserved.17 18. Entities andRelationships Persistence-by-reachability In JPA, when object is persisted, no related entities are persisted automatically by default. There are two options: Call persist method for each entity separately Use cascading to extend persistence reachabilityCopyright 2009 Accenture All Rights Reserved.18 19. Cascading Persistence operation are applied to specified entities. Similar to cascade deletes known from PL/SQL. There are many types of cascades: PERSIST MERGE REMOVE REFRESH ALL ( = PERSIST + MERGE + REMOVE + REFRESH)Copyright 2009 Accenture All Rights Reserved. 19 20. Cascading Example: @Entity public class Customer { @OneToOne( cascade = CascadeType.ALL ) private IDCard idCard; @OneToMany(mappedBy = custId,cascade = { CascadeType.PERSIST, CascadeType.MERGE } ) private List orders; // ... }Copyright 2009 Accenture All Rights Reserved.20 21. One-to-Onerelationshipa) Unidirectional@OneToOne@JoinColumn(name=address_id)Copyright 2009 Accenture All Rights Reserved.21 22. One-to-One relationship(unidirectional)@Entitypublic class Customer implements Serializable {@Idprivate Integer id;private String firstName;private String lastName;@OneToOne@JoinColumn(name=address_id)private Address address;}@Entitypublic class Address implements Serializable {@Idprivate Integer id;@Column(name=street_name)private String street;private String city;}Copyright 2009 Accenture All Rights Reserved. 22 23. One-to-Onerelationshipb) Bidirectional FK owner side (Customer): @OneToOne @JoinColumn(name=address_id)non-owner side (Address):@OneToOne(mappedBy=address)Copyright 2009 Accenture All Rights Reserved. 23 24. One-to-One relationship(bidirectional)@Entitypublic class Customer implements Serializable {@Idprivate Integer id;private String firstName;private String lastName;@OneToOne@JoinColumn(name=address_id)private Address address;}@Entitypublic class Address implements Serializable {@Idprivate Integer id;private String street_name;private String street_num;private String city;@OneToOne(mappedBy=address)private Customer cust;}Copyright 2009 Accenture All Rights Reserved. 24 25. One-to-Manyrelationship Can be unidirectional or bidirectional Several data types can be used for relationship representation: Collection Set List Map There are 2 ways how to define One-to-Many relationship: using Foreign key using Join tableCopyright 2009 Accenture All Rights Reserved. 25 26. One-to-Manyrelationshipa) Using Foreign key (only Bidirectional) FK non-owner side (Customer): @OneToMany(mappedBy=cust)FK owner side (Phone):@ManyToOne@JoinColumn(name=cust_id)Copyright 2009 Accenture All Rights Reserved.26 27. One-to-Many relationship(foreign key)@Entitypublic class Customer implements Serializable {@Idprivate Integer id;private String firstName;private String lastName;@OneToMany(mappedBy=cust)private List phones;}@Entitypublic class Phone implements Serializable {@Idprivate Integer id;private String prefix;private String phoneNum;@ManyToOne@JoinColumn(name=cust_id)private Customer cust;}Copyright 2009 Accenture All Rights Reserved.27 28. One-to-Manyrelationshipb) Using join table (unidirectional) Collection owner (Customer): @OneToMany @JoinTable(name=customer_phone )Copyright 2009 Accenture All Rights Reserved.28 29. One-to-Many relationship(unidirectional)@Entitypublic class Customer implements Serializable {@Idprivate Integer id;private String firstName;private String lastName;@OneToMany@JoinTable(name=customer_phone, joinColumns = @JoinColumn(name=cust_id, inverseJoinColumns = @JoinColumn(name=phone_id))private List phones;}@Entitypublic class Phone implements Serializable {@Idprivate Integer id;private String prefix;private String phonenum;}Copyright 2009 Accenture All Rights Reserved.29 30. One-to-Manyrelationshipc) Using join table (bidirectional) Collection owner (Customer): @OneToMany(mappedBy=cust) @JoinTable(name=customer_phone )FK owner side (Phone):@ManyToOneCopyright 2009 Accenture All Rights Reserved.30 31. One-to-Many relationship(bidirectional)@Entitypublic class Customer implements Serializable {@Idprivate Integer id;private String firstName;private String lastName;@OneToMany(mappedBy=cust)@JoinTable(name=customer_phone,joinColumns = @JoinColumn(name=cust_id,inverseJoinColumns = @JoinColumn(name=phone_id))private List phones;}@Entitypublic class Phone implements Serializable {@Idprivate Integer id;private String prefix;private String phonenum;@ManyToOneprivate Customer cust;}Copyright 2009 Accenture All Rights Reserved.31 32. Many-to-OnerelationshipUsing Foreign key FK owner side (Customer): @ManyToOne @JoinColumn(name=address_id)Copyright 2009 Accenture All Rights Reserved. 32 33. Many-to-Onerelationship@Entitypublic class Customer implements Serializable {@Idprivate Integer id;private String firstName;private String lastName;@ManyToOne@JoinColumn(name=address_id)private Address address;}@Entitypublic class Address implements Serializable {@Idprivate Integer id;private String street_name;private String street_num;private String city;}Copyright 2009 Accenture All Rights Reserved.33 34. Many-to-ManyrelationshipUsing join table Employee: @ManyToMany @JoinTable(name=employee_project )FK owner side (Address):@ManyToMany(mappedBy=employees)Copyright 2009 Accenture All Rights Reserved.34 35. Many-to-Manyrelationship@Entitypublic class Employee implements Serializable {@Idprivate Integer id;private String firstName;private String lastName;@ManyToMany@JoinTable(name=employee_project,joinColumns = @JoinColumn(name=emp_id,inverseJoinColumns = @JoinColumn(name=prj_id))private Collection projects;}@Entitypublic class Project implements Serializable {@Idprivate Integer id;private String name;private String status;@ManyToOne(mappedBy=projects)private Collection employees;}Copyright 2009 Accenture All Rights Reserved.35 36. Persistence operations &query languageAll operations are managed by EntityManager is instantiated using EntityManager Factory based on persistence unit name (persistence.xml)To instantiate EntityManager:EntityManagerFactory emf =Persistence.createEntityManagerFactory(PersistenceUnit);EntityManager mng = emf.createEntityManager();Copyright 2009 Accenture All Rights Reserved.36 37. Entity Manager Entity lifecycleCopyright 2009 Accenture All Rights Reserved.37 38. Entity Manager CRUD operations Create: persist(Object obj) ~ INSERT Read: T find(Class cls, Object id) ~ SELECT Update: T merge(T t) ~ UPDATE Delete: remove(Object obj) ~ DELETECopyright 2009 Accenture All Rights Reserved.38 39. Entity Manager CRUD operationspersist(Object obj)- persists object into DB (new records)Example:Customer cust = new Customer();cust.setFirstName(John);cust.setLastName(Smith);entityManager.persist(cust);Copyright 2009 Accenture All Rights Reserved.39 40. Entity Manager CRUD operationsT find(Class cls, Object id)-finds record of given in DB-returns instance of class cls or nullExample:Integer customerId = 123;Class cls = Customer.class;Customer cust = entityManager.find(cls, customerId);Copyright 2009 Accenture All Rights Reserved.40 41. Entity Manager CRUD operationsT merge(T obj)-to update existing record-returns updated EntityExample:Integer customerId = 123;Class cls = Customer.class;Customer cust = entityManager.find(cls, customerId);cust.setFirstName(John jr);entityManager.merge(cust);Copyright 2009 Accenture All Rights Reserved.41 42. Entity Manager CRUD operationsremove(Object obj)- removes object from DBExample:Integer customerId = 123;Class cls = Customer.class;Customer cust = entityManager.find(cls, customerId);entityManager.remove(cust);Copyright 2009 Accenture All Rights Reserved.42 43. Entity Manager CRUD operationsrefresh(Object obj)- retrieves actual state of object from DBExample:Integer customerId = 123;Class cls = Customer.class;Customer cust = entityManager.find(cls, customerId);...entityManager.refresh(cust);Copyright 2009 Accenture All Rights Reserved.43 44. Entity Manager CRUD operationsCallbacks for Persistence operations: @PrePersist @PostPersist @PostLoad @PreUpdate @PostUpdate @PreRemove @PostRemoveCopyright 2009 Accenture All Rights Reserved.44 45. Entity Manager CRUD operationsCallbacks for Persistence operations:@Entity@EntityListeners({CustomerListener.class})public class Customer {@Id private Integer id;@PreUpdateprivate void something() {System.out.println(before update...);}}public class CustomerListener {@PostUpdatepublic void postUpdate(Customer cust) {System.out.println(after update...);}}Copyright 2009 Accenture All Rights Reserved.45 46. Entity ManagerQueries Query language similar to SQL Query Named Query Native QueryCopyright 2009 Accenture All Rights Reserved.46 47. Entity Manager QueriesQuery simple query (one-time use) parameters wildcards % and _ are supportedExample:String jql = SELECT c FROM Customer c WHERE c.firstName LIKE ?;Query query = entityManager.createQuery(jql);query.setParameter(1, J%);List customers = query.getResultList();Copyright 2009 Accenture All Rights Reserved. 47 48. Entity Manager QueriesNamed Query precompiled query@Entity@NamedQueries({ @NamedQuery( name=findByLastName, query=SELECT c FROM Customer c WHERE c.lastName = :lstName)})public class Customer {}Query query = entityManager.createNamedQuery(findByLastName);query.setParameter(lstName, Smith);List customers = query.getResultList();Copyright 2009 Accenture All Rights Reserved.48 49. Entity Manager QueriesNative Query@Entity@Table(name=CUSTOMER@NamedNativeQuery(name=nativeQuery,query=SELECT c.id FROM customer c WHERE c.lastName = ?),resultClass = Customer.class)public class Customer {}Query query = entityManager.createNativeQuery(nativeQ);query.setParameter(1, Smith);List customers = query.getResultList();Copyright 2009 Accenture All Rights Reserved.49 50. TransactionsThere are two ways to handle transactions: by application (SE) by JTA (EE)orCopyright 2009 Accenture All Rights Reserved.50 51. TransactionsEntityManger methods: begin() commit() setRollbackOnly() rollback() isActive()Copyright 2009 Accenture All Rights Reserved.51 52. TransactionsExample:Transaction t = mng.getTransaction();try { t.begin(); mng.persist(obj1); mng.persist(obj2); mng.commit();}catch (Exception e) {mng.setRollbackOnly(true);}finally {if (t.isRollbackOnly) t.rollback();}Copyright 2009 Accenture All Rights Reserved.52 53. LockingTo avoid concurrency access, two types oflocking are available in JPA: Optimistic locking Pessimistic locking (JPA2.0)Copyright 2009 Accenture All Rights Reserved. 53 54. Optimistic LockingChecks if record has been updated by differenttransaction (right before performing operation) lock() method lock modes: READ (OPTIMISTIC in JPA2.0) WRITE (OPTIMISTIC_FORCE_INCREMENT)Copyright 2009 Accenture All Rights Reserved.54 55. Optimistic LockingExample:@Entitypublic class Customer implements Serializable {...@Versionprivate Timestamp lastUpdateTimestamp;}try {Customer cust = mng.find(Customer.class, 123);mng.lock(cust, WRITE); OPTIMISTIC_FORCE_INCREMENT in JPA2.0// some update here...mng.merge(cust);transaction.commit();}catch (OptimisticLockException e) {System.out.println(Concurrent update detected!);}Copyright 2009 Accenture All Rights Reserved. 55 56. Pessimistic LockingExplicitly locks records in DB to avoid update bydifferent transaction. Available from JPA2.0. lock() method lock modes: PESSIMISTIC PESSIMISTIC_FORCE_INCREMENTCopyright 2009 Accenture All Rights Reserved. 56 57. Pessimistic LockingExample 1 Lock after read:...Customer cust = mng.find(Customer.class, custId);mng.lock(cust, PESSIMISTIC);// some update here...mng.merge(cust);transaction.commit();...! Risk:Since we first read and lock afterwards, an OptimisticException can occurif another transaction updates record meanwhile.Copyright 2009 Accenture All Rights Reserved. 57 58. Pessimistic LockingExample 2 Lock during read:...Customer cust =mng.find(Customer.class, custId, PESSIMISTIC);// some update here...mng.merge(cust);transaction.commit();...! Risks:Records are locked longer. Risk of bottlenecks and deadlocks; badscalability.Copyright 2009 Accenture All Rights Reserved. 58 59. Pessimistic LockingExample 3 Read, lock and refresh:...Customer cust = mng.find(Customer.class, custId);mng.refresh(cust, PESSIMISTIC);// some update here...mng.merge(cust);transaction.commit();...Advantage:Lock is acquired only for time required for update.Copyright 2009 Accenture All Rights Reserved. 59 60. DemoCopyright 2009 Accenture All Rights Reserved. 60 61. Questions & CommentsTwo options to ask a question or add your comments to the discussion: Use Raise Hand and then hold down the TALK icon or press theCopyright 2009CTRL key; release when doneAccenture your question in the Chat Room Post All RightsReserved. 62. Thank you forparticipating!