En webinar jpa v2final

445 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
445
On SlideShare
0
From Embeds
0
Number of Embeds
42
Actions
Shares
0
Downloads
25
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • The Centra tools displayed on this slide are the tools you can use to interact with the participants during this session. The RAISE YOUR HAND icon is used to ask questions or make comments. Once a participant “raises their hand”, the presenter or moderator will then call on them to speak. In order to speak, you must be given a microphone. Once the microphone is granted, you can speak by holding down the control key on your keyboard. Go ahead and click this icon now. The YES/NO icons are used to answer simple yes/no or true/false questions. Please go ahead and click these icons now. Feel free to indicate APPLAUSE or LAUGHTER during the session by choosing the applicable icons. “ The CHAT icon is an important icon. It will be used to communicate with the participants as well as the presenters. Please click on it now and resize it and move to the right side of the screen to see the Centra presentation and the chat room at the same time. There are several options on how to send your Text Chat message. We will focus on selecting “ALL” in the dropdown list. “All” is an open public forum where all messages will be displayed to both participants and presenters. Please enter your location today. [Pause: wait for participants to type messages into the chat room.] “ If you experience volume issues, you can use the Centra Volume Control. We recommend setting the bar to mid point or less for optimal audio.” “ There is also a Network Connectivity Bar at the lower right hand side of your screen. Since Centra is a real-time stream over the network, it is impacted by your network connection. This bar indicates the quality of your network connection. To ensure the best experience possible, please review the listed Audio/Connectivity Tips.
  • You have two options today to ask questions. To ask questions live and speak via VOIP you should Press the Raise Hand icon to get the faculty’s attention. Once called up, you would hold down the Talk icon or the CTRL key and then release when done. Or you can post your question into the Text Chat at any time.
  • “ Thank you very much for your participation in the session today. I’d also like to thank our presenters for their time and expertise.” “ When you log out you’ll be taken to a session evaluation – please take a few minutes to fill it out. Your feedback is appreciated. Thanks again for joining us. Have a good day.”
  • En webinar jpa v2final

    1. 1. Java Persistence API Emil Nahlik (DC Bratislava)Copyright © 2009 Accenture All Rights Reserved.
    2. 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 Chat your signal is as strong as possible • Monitor the Network ConnectivityCentra Volume Control Bar • Contact Learning Product Support if issues continueNetwork Connectivity Bar
    3. 3. Asking QuestionsTwo Options: 1. Ask live questions during the designated Q&A sessions: • Press Raise Hand icon to get faculty’s 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. 4. Session structure • Introduction • Basic JPA Configuration • Entity relationships • Persistence operations and query language • Transactions & optimistic/pessimistic locking • Demo •Q & ACopyright © 2009 Accenture All Rights Reserved. 4
    5. 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. 6. Introduction There is no need to run an application server to use JPA. It can run as a stand alone, you need just a JPA implementation and properly configured XML file.Copyright © 2009 Accenture All Rights Reserved. 6
    7. 7. Basic JPA Configuration What does a typical JPA project consists of? • JPA implementation • Entities • Entity manager • Configuration file – persistence.xmlCopyright © 2009 Accenture All Rights Reserved. 7
    8. 8. JPA Implementation There are many JPA implementations: • OpenJPA • Hibernate • TopLink • CocoBase • Castor • JPOX • etc.Copyright © 2009 Accenture All Rights Reserved. 8
    9. 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. 10. Entities Example: @Entity public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id private Integer id; private String firstName; private String lastName; }Copyright © 2009 Accenture All Rights Reserved. 10
    11. 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. 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. 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. 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. 15. Configuration file <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns=http://java.sun.com/xml/ns/persistence> <persistence-unit name=“MyPersistenceUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <non-jta-data-source>TEST_DB</non-jta-data-source> <class>jpa.webinar.entities.Person</class> <class>jpa.webinar.entities.Address</class> <class>jpa.webinar.entities.PhoneNumber</class> <!-- Hibernate properties --> <properties> <property name="hibernate.dialect“ value="org.hibernate.dialect.Oracle10gDialect"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> </properties> </persistence-unit> </persistence>Copyright © 2009 Accenture All Rights Reserved. 15
    16. 16. Entities and Relationships There are many types of relationships: • 1-to-1 – unidirectional (AB) / bidirectional (AB) • 1-to-N – unidirectional / bidirectional • N-to-1 – unidirectional / bidirectional • M-to-N – always bidirectionalCopyright © 2009 Accenture All Rights Reserved. 16
    17. 17. Entities and Relationships Unidirectional relationship Bidirectional relationship 1-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 sides of relationship!Copyright © 2009 Accenture All Rights Reserved. 17
    18. 18. Entities and Relationships 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. 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. 20. Cascading Example: @Entity public class Customer { @OneToOne( cascade = CascadeType.ALL ) private IDCard idCard; @OneToMany(mappedBy = “custId”, cascade = { CascadeType.PERSIST, CascadeType.MERGE } ) private List<Order> orders; // ... }Copyright © 2009 Accenture All Rights Reserved. 20
    21. 21. One-to-One relationship a) Unidirectional @OneToOne @JoinColumn(name=“address_id”)Copyright © 2009 Accenture All Rights Reserved. 21
    22. 22. One-to-One relationship (unidirectional) @Entity public class Customer implements Serializable { @Id private Integer id; private String firstName; private String lastName; @OneToOne @JoinColumn(name=“address_id”) private Address address; } @Entity public class Address implements Serializable { @Id private Integer id; @Column(name=“street_name”) private String street; private String city; }Copyright © 2009 Accenture All Rights Reserved. 22
    23. 23. One-to-One relationship b) 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. 24. One-to-One relationship (bidirectional) @Entity public class Customer implements Serializable { @Id private Integer id; private String firstName; private String lastName; @OneToOne @JoinColumn(name=“address_id”) private Address address; } @Entity public class Address implements Serializable { @Id private 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. 25. One-to-Many relationship • 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. 26. One-to-Many relationship a) 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. 27. One-to-Many relationship (foreign key) @Entity public class Customer implements Serializable { @Id private Integer id; private String firstName; private String lastName; @OneToMany(mappedBy=“cust”) private List<Phone> phones; } @Entity public class Phone implements Serializable { @Id private Integer id; private String prefix; private String phoneNum; @ManyToOne @JoinColumn(name=“cust_id”) private Customer cust; }Copyright © 2009 Accenture All Rights Reserved. 27
    28. 28. One-to-Many relationship b) Using join table (unidirectional) Collection owner (Customer): @OneToMany @JoinTable(name=“customer_phone” …)Copyright © 2009 Accenture All Rights Reserved. 28
    29. 29. One-to-Many relationship (unidirectional) @Entity public class Customer implements Serializable { @Id private 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<Phone> phones; } @Entity public class Phone implements Serializable { @Id private Integer id; private String prefix; private String phonenum; }Copyright © 2009 Accenture All Rights Reserved. 29
    30. 30. One-to-Many relationship c) 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. 31. One-to-Many relationship (bidirectional) @Entity public class Customer implements Serializable { @Id private 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<Phone> phones; } @Entity public class Phone implements Serializable { @Id private Integer id; private String prefix; private String phonenum; @ManyToOne private Customer cust; }Copyright © 2009 Accenture All Rights Reserved. 31
    32. 32. Many-to-One relationship Using Foreign key FK owner side (Customer): @ManyToOne @JoinColumn(name=“address_id”)Copyright © 2009 Accenture All Rights Reserved. 32
    33. 33. Many-to-One relationship @Entity public class Customer implements Serializable { @Id private Integer id; private String firstName; private String lastName; @ManyToOne @JoinColumn(name=“address_id”) private Address address; } @Entity public class Address implements Serializable { @Id private Integer id; private String street_name; private String street_num; private String city; }Copyright © 2009 Accenture All Rights Reserved. 33
    34. 34. Many-to-Many relationship Using join table Employee: @ManyToMany @JoinTable(name=“employee_project” …) FK owner side (Address): @ManyToMany(mappedBy=“employees”)Copyright © 2009 Accenture All Rights Reserved. 34
    35. 35. Many-to-Many relationship @Entity public class Employee implements Serializable { @Id private 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<Project> projects; } @Entity public class Project implements Serializable { @Id private Integer id; private String name; private String status; @ManyToOne(mappedBy=“projects”) private Collection<Employee> employees; }Copyright © 2009 Accenture All Rights Reserved. 35
    36. 36. Persistence operations & query language All 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. 37. Entity Manager – Entity lifecycleCopyright © 2009 Accenture All Rights Reserved. 37
    38. 38. Entity Manager – CRUD operations • Create: persist(Object obj) ~ INSERT • Read: T find(Class<T> cls, Object id) ~ SELECT • Update: T merge(T t) ~ UPDATE • Delete: remove(Object obj) ~ DELETECopyright © 2009 Accenture All Rights Reserved. 38
    39. 39. Entity Manager – CRUD operations persist(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. 40. Entity Manager – CRUD operations T find(Class<T> cls, Object id) -finds record of given in DB -returns instance of class cls or null Example: Integer customerId = 123; Class cls = Customer.class; Customer cust = entityManager.find(cls, customerId);Copyright © 2009 Accenture All Rights Reserved. 40
    41. 41. Entity Manager – CRUD operations T merge(T obj) -to update existing record -returns updated Entity Example: 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. 42. Entity Manager – CRUD operations remove(Object obj) - removes object from DB Example: Integer customerId = 123; Class cls = Customer.class; Customer cust = entityManager.find(cls, customerId); entityManager.remove(cust);Copyright © 2009 Accenture All Rights Reserved. 42
    43. 43. Entity Manager – CRUD operations refresh(Object obj) - retrieves actual state of object from DB Example: Integer customerId = 123; Class cls = Customer.class; Customer cust = entityManager.find(cls, customerId); ... entityManager.refresh(cust);Copyright © 2009 Accenture All Rights Reserved. 43
    44. 44. Entity Manager – CRUD operations Callbacks for Persistence operations: • @PrePersist • @PostPersist • @PostLoad • @PreUpdate • @PostUpdate • @PreRemove • @PostRemoveCopyright © 2009 Accenture All Rights Reserved. 44
    45. 45. Entity Manager – CRUD operations Callbacks for Persistence operations: @Entity @EntityListeners({CustomerListener.class}) public class Customer { @Id private Integer id; @PreUpdate private void something() { System.out.println(“before update...”); } } public class CustomerListener { @PostUpdate public void postUpdate(Customer cust) { System.out.println(“after update...”); } }Copyright © 2009 Accenture All Rights Reserved. 45
    46. 46. Entity Manager Queries • Query language similar to SQL • Query • Named Query • Native QueryCopyright © 2009 Accenture All Rights Reserved. 46
    47. 47. Entity Manager – Queries Query – simple query (one-time use) • parameters • wildcards % and _ are supported Example: String jql = “SELECT c FROM Customer c WHERE c.firstName LIKE ?”; Query query = entityManager.createQuery(jql); query.setParameter(1, “J%”); List<Customer> customers = query.getResultList();Copyright © 2009 Accenture All Rights Reserved. 47
    48. 48. Entity Manager – Queries Named 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<Customer> customers = query.getResultList();Copyright © 2009 Accenture All Rights Reserved. 48
    49. 49. Entity Manager – Queries Native 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<Customer> customers = query.getResultList();Copyright © 2009 Accenture All Rights Reserved. 49
    50. 50. Transactions There are two ways to handle transactions: • by application (SE) • by JTA (EE) <persistence-unit name=“MyUnit" transaction-type="RESOURCE_LOCAL"> or <persistence-unit name=“MyUnit" transaction-type=“JTA">Copyright © 2009 Accenture All Rights Reserved. 50
    51. 51. Transactions EntityManger methods: • begin() • commit() • setRollbackOnly() • rollback() • isActive()Copyright © 2009 Accenture All Rights Reserved. 51
    52. 52. Transactions Example: 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. 53. Locking To avoid concurrency access, two types of locking are available in JPA: • Optimistic locking • Pessimistic locking (JPA2.0)Copyright © 2009 Accenture All Rights Reserved. 53
    54. 54. Optimistic Locking Checks if record has been updated by different transaction (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. 55. Optimistic Locking Example: @Entity public class Customer implements Serializable { ... @Version private 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. 56. Pessimistic Locking Explicitly locks records in DB to avoid update by different transaction. Available from JPA2.0. • lock() method • lock modes: – PESSIMISTIC – PESSIMISTIC_FORCE_INCREMENTCopyright © 2009 Accenture All Rights Reserved. 56
    57. 57. Pessimistic Locking Example 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 occur if another transaction updates record meanwhile.Copyright © 2009 Accenture All Rights Reserved. 57
    58. 58. Pessimistic Locking Example 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; bad scalability.Copyright © 2009 Accenture All Rights Reserved. 58
    59. 59. Pessimistic Locking Example 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. 60. DemoCopyright © 2009 Accenture All Rights Reserved. 60
    61. 61. Questions & Comments Two 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 © 2009 CTRL key; release when doneAccenture your question in the Chat Room  Post All RightsReserved.
    62. 62. Thank you forparticipating!

    ×