SlideShare ist ein Scribd-Unternehmen logo
1 von 84
Java Persistence API: Best Practices Carol McDonald Java Architect
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object]
Persistence  Context EntityManager persist() remove() refresh() merge() find() createQuery() createNamedQuery() contains() flush() EntityManager  API for managing entities ,[object Object],[object Object],Servlets EJBs Java app
Catalog Java EE  Application DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean
EJB EntityManager Example  @Stateless public class  Catalog  implements  CatalogService  { @PersistenceContext(unitName=”PetCatalogPu”)   EntityManager em; @TransactionAttribute(NOT_SUPPORTED) public List<Item>  getItems (int  firstItem , int  batchSize ) {  Query  q =  em . createQuery (&quot; select i from Item as i &quot;);  q. setMaxResults ( batchSize ); q. setFirstResult ( firstItem ); List<Item> items= q.getResultList(); return items;  } }
Catalog Spring JPA Application DB Registration Application Managed Bean JSF Components Spring  Bean Entity Class Catalog Item ItemController Spring Framework
Spring  with JPA @Repository @Transactional public class CatalogDAO implements  CatalogService  { @PersistenceContext (unitName=&quot;PetCatalogPu&quot;) private  EntityManager em; @Transactional(readOnly=true) public List<Item>  getItems (int firstItem,int batchSize) {    Query q =    em. createQuery(&quot;select object(o) from Item as o&quot;);   q.setMaxResults(batchSize);   q.setFirstResult(firstItem);   List<Item> items= q.getResultList();   return items;  } Component Stereotype Spring transactions use aop
Container vs Application Managed  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object]
Persistence  Context EntityManager persist() remove() refresh() merge() find() createQuery() createNamedQuery() contains() flush() Persistence Context  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Level1 and Level2 caches The terms “Java Virtual Machine” and “JVM” mean a Virtual Machine for the Java ™  Platform. Source:http://weblogs.java.net/blog/guruwons/archive/2006/09/understanding_t.html Persistence Context is a Level 1 cache Transaction  Transaction  Transaction  Persistence Context (EntityManager) Persistence Context (EntityManager) Persistence Context (EntityManager) L2 Cache (Shared Cache) Entity managers for a specific PersistenceUnit on a given Java Virtual Machine (JVM ™ )
Persistence Context ,[object Object],new() persist() Updates remove() Merge() find() PC ends Entity Lifecycle  Guaranteed Scope of  Object Identity  only  one  manage entity  in PC represents a row
Entity Lifecycle Illustrated – The Code @Stateless  public ShoppingCartBean implements ShoppingCart { @PersistenceContext   EntityManager entityManager; public OrderLine createOrderLine(Product product , Order order) { O rderLine orderLine = new OrderLine(order, product); entityManager.persist(orderLine); return (orderLine); } } New entity Managed entity Detached entity Persistence context
Scope of Identity @Stateless  public ShoppingCartBean  implements ShoppingCart { @PersistenceContext   EntityManager entityManager; public OrderLine createOrderLine( Product product,Order order) { O rderLine orderLine = new OrderLine(order, product); entityManager.persist(orderLine); OrderLine  orderLine2  = entityManager.find (OrderLine, orderLine.getId()) ); ( orderLine == orderLine2 ) // TRUE return (orderLine); } } Persistence context Multiple retrievals of the same object return references to the  same object instance
Persistence Context ,[object Object],[object Object],[object Object],[object Object],[object Object]
Persistence Context Propagation ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Persistence context
Persistence Context Propagation ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Declarative Transaction Management Example TX_REQUIRED TX_REQUIRED TX_REQUIRED PC PC PC Shopping Cart Inventory Service Order Service Check Out 1. Update Inventory New Persistence Context Persistence Context  Propagated Transaction Attributes 2. Create Order
AuditServiceBean  @Stateless public class AuditServiceBean implements AuditService { @PersistenceContext private EntityManager em; @TransactionAttribute(REQUIRES_NEW) public void logTransaction2(int id, String action) { LogRecord lr = new LogRecord(id, action); em.persist(lr); } NEW PC !
Declarative Transaction Management Example 2 REQUIRED REQUIRED REQUIRES_NEW PC PC PC2 Shopping Cart Inventory Service Audit Service Check Out 1. Update Inventory New Persistence Context Persistence Context  Propagated Transaction Attributes 2. log transaction  NEW PC !
Persistence Provider PC Transaction Features ,[object Object],[object Object],[object Object],[object Object],[object Object]
Persistence Context Conversation with detached entity  Persistence Context merge() transaction-scoped  persistence context request response request response Conversation transaction-scoped  persistence context
Conversation with detached entity @Stateless  public ShoppingCartBean  implements ShoppingCart  { @PersistenceContext   EntityManager entityManager; public OrderLine createOrderLine(Product product,Order order) { OrderLine orderLine = new OrderLine(order, product); entityManager.persist (orderLine); return ( orderLine ); } public OrderLine updateOrderLine(OrderLine  orderLine ){ OrderLine  orderLine2  = entityManager.merge (orderLine) ); return  orderLine2 ; } } Managed entity Detached entity Managed entity
Types of Persistence Context ,[object Object],[object Object],[object Object],[object Object],[object Object]
Persistence Context Conversation with Exented Persistence Context request response request response Conversation extended  persistence context
Extended Persistence Context @Stateful  public class  OrderMgr  { //Specify that we want an EXTENDED   @PersistenceContext (type=PersistenceContextType.EXTENDED) EntityManager em ; //Cached order private Order  order ; //create and cache order public void createOrder(String itemId) { //order remains managed for the lifetime of the bean Order order = new Order(cust); em.persist( order ); } public void  addLineItem (OrderLineItem li){ order. lineItems.add(li); } Managed entity Managed entity
Extended Persistence Context @Stateful  public class DeptMgr { @PersistenceContext (type=PersistenceContextType.EXTENDED) EntityManager em ; private Department dept; @TransactionAttribute(NOT_SUPPORTED) public void getDepartment(int deptId) { dept  = em.find(Department.class,deptId); } @TransactionAttribute(NOT_SUPPORTED) public void  addEmployee (int empId){ emp  = em.find(Employee.class,empId); dept.getEmployees().add(emp); emp.setDepartment(dept); } @Remove @TransactionAttribute(REQUIRES_NEW) public void endUpdate(int deptId) { dept  = em.find(Department.class,deptId); }
Persistence Context- Transactional vs. Extended @Stateless public class  OrderMgr  implements OrderService { @PersistenceContext EntityManager em;  public void  addLineItem (OrderLineItem li){  // First, look up the order. Order order = em.find(Order.class, orderID); order.lineItems.add(li); } @Stateful public class  OrderMgr  implements OrderService { @PersistenceContext(type = PersistenceContextType. EXTENDED )) EntityManager em;   // Order is cached Order order public void  addLineItem (OrderLineItem li){ // No em.find invoked for the order object  order.lineItems.add(li); } look up the order No em.find invoked  Managed entity
Persistence Context Micro Benchmark ,[object Object],[object Object],Source: Internal benchmarks
SEAM Conversations  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],SEAM injected  SEAM conversation
Concurrency and Persistence Context  Object Identity  only  one  manage entity  in PC  represents a row  User  2 transaction User 1  transaction Persistence Context 1 Entity Manager Persistence Context 2 Entity Manager Data source same entity
Optimistic versus Pessimistic Concurrency ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Preventing Parallel Updates ,[object Object],[object Object],[object Object],[object Object],[object Object],public class Employee { @ID int id; @Version int version; ... ,[object Object]
Preventing Parallel Updates – 1 ,[object Object],[object Object],[object Object],[object Object],[object Object],Time
Preventing Stale Data JPA 1.0 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Preventing Stale Data ,[object Object],[object Object],Time
[object Object],[object Object],[object Object],[object Object],[object Object],Preventing Parallel Updates – 2  Time
Bulk Updates ,[object Object],[object Object],[object Object],[object Object],[object Object]
JPA 2.0 Locks ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],database locks the row  (SELECT . . . FOR UPDATE )
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],JPA  2.0 Locking  Locks  longer , could cause  bottlenecks, deadlock Lock after read, risk  stale , could cause  OptimisticLock Exception
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],JPA  2.0 Locking  “ right” approach depends on requirements ,[object Object],[object Object],[object Object]
L2 cache shared across transactions and users Putting it all together User Session  User Session  User Session Persistence Context (EntityManager) Persistence Context (EntityManager) Persistence Context (EntityManager) L2 Cache (Shared Cache) Entity managers for a specific PersistenceUnit on a given Java Virtual Machine (JVM ™ ) (EntityManagerFactory)
Second-level Cache ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
L2 Cache L2  Cache query that looks for a single object based on  Id  will go  1st  to  PC  then to  L2  cache, other queries go to  database  or query cache Shared entity User transaction 1 Persistence Context User transaction 2 Persistence Context Data source same entity not shared
L2 Caching ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
L2 Caching ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
JPA 2.0 Shared Cache API ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
EclipseLink Caching Architecture EclipseLink caches Entities  in L2, Hibernate does not  EntityManager EntityManager Factory Server L1 Cache PC Cache L2 Shared Cache Cache Coordination JMS (MDB) RMI  CORBA IIOP
EclipseLink Extensions - L2 Caching ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],EclipseLink Mapping Extensions   Type= Full:  objects never flushed unless deleted or evicted weak:  object will be garbage collected if not referenced ,[object Object],[object Object],[object Object],=true disables L2 cache
Hibernate  L2 Cache ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Cache Concurrency Strategy
Hibernate  L2 Cache ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],not configured by default  Cache Concurrency Strategy must be supported by cache provider
OpenJPA L2  Caching ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object]
Maintaining Relationship ,[object Object],deptA.getEmployees().add(e3); Department A Employee1 Employee2 Employee3 Employee1 Employee2 Employee3 Before After Inconsistent! Department B Department A Department B
Example – Domain Model @Entity public class Employee { @Id private int id; private String firstName; private String lastName; @ManyToOne(fetch=LAZY) private Department dept;   ... } @Entity public class Department { @Id private int id; private String name; @OneToMany(mappedBy = &quot;dept&quot;, fetch=LAZY) private Collection<Employee> emps = new ...;   ... }
Example – Managing Relationship public int addNewEmployee(...) { Employee e = new Employee(...); Department d = new Department(1, ...); e.setDepartment(d); //Reverse relationship is not set em.persist(e); em.persist(d); return  d.getEmployees().size(); } INCORRECT
Example – Managing Relationship public int addNewEmployee(...) { Employee e = new Employee(...); Department d = new Department(1, ...); e.setDepartment(d); d.getEmployees().add(e); em.persist(e); em.persist(d); return  d.getEmployees().size(); } CORRECT
Navigating Relationships ,[object Object],[object Object],[object Object],[object Object]
Lazy loading and JPA ,[object Object],[object Object],[object Object],[object Object],@Entity public class Department { @Id private int id; @OneToMany(mappedBy = &quot;dept&quot;) private Collection<Employee> emps ;   ... } SELECT  d.id, ... FROM Department d  // 1 time SELECT  e.id, ... FROM Employee e  WHERE e.deptId = ?  // N times
Lazy loading and JPA ,[object Object],[object Object],[object Object],[object Object],@Entity public class Department { @Id private int id; @OneToMany(mappedBy = &quot;dept&quot;,  fetch=EAGER ) private Collection<Employee> employees  ;   ... } @NamedQueries ({ @NamedQuery(name=&quot;getItEarly&quot;,  query=&quot;SELECT d FROM  Department  d  JOIN FETCH   d.employees &quot;)}) public class  Department { ..... } Can cause Cartesian product
Lazy loading and JPA ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Navigating Relationships ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],d.getEmployees().size(); Persistence  Context
Navigating Relationships ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Using Cascade @Entity public class Employee { @Id private int id; private String firstName; private String lastName; @ManyToOne( cascade=ALL , fetch=LAZY) private Department dept;   ... } @Entity public class Department { @Id private int id; private String name; @OneToMany(mappedBy = &quot;dept&quot; cascade=ALL , fetch=LAZY) private Collection<Employee> emps = new ...; @OneToMany private Collection<DepartmentCode> codes;   ... } Employee Department DepartmentCode cascade=ALL X
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object]
Database design Basic foundation of performance ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Normalization ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Mapping Inheritance Hierarchies Employee --------------------------- int id  String firstName String lastName  Department dept PartTimeEmployee ------------------------ int rate FullTimeEmployee ----------------------- double salary
Single Table Per Class ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],@Inheritance(strategy=SINGLE_TABLE) EMPLOYEE --------------------------- ID Int PK, FIRSTNAME varchar(255), LASTNAME varchar(255),  DEPT_ID int FK, RATE int NULL, SALARY double NULL, DISCRIM varchar(30)
Joined Subclass ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],@Inheritance(strategy=JOINED) ID int PK, FIRSTNAME varchar(255), LASTNAME varchar(255),  DEPT_ID int FK, ID int PK FK, RATE int NULL ID int PK FK, SALARY double NULL EMPLOYEE PARTTIMEEMPLOYEE FULLTIMEEMPLOYEE
Table Per Class ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],@Inheritance(strategy=TABLE_PER_CLASS) ID int PK, FIRSTNAME varchar(255), LASTNAME varchar(255), DEPT_ID int FK, SALARY double NULL ID int PK, FIRSTNAME varchar(255), LASTNAME varchar(255), DEPT_ID int FK, RATE int NULL PARTTIMEEMPLOYEE FULLTIMEEMPLOYEE
vertical partitioning ,[object Object],[object Object],CREATE TABLE  Customer ( user_id  INT NOT NULL AUTO_INCREMENT , email  VARCHAR(80) NOT NULL , display_name  VARCHAR(50) NOT NULL , password  CHAR(41) NOT NULL , first_name  VARCHAR(25) NOT NULL , last_name  VARCHAR(25) NOT NULL , address  VARCHAR(80) NOT NULL , city  VARCHAR(30) NOT NULL , province  CHAR(2) NOT NULL , postcode  CHAR(7) NOT NULL , interests  TEXT NULL , bio  TEXT NULL , signature  TEXT NULL , skills  TEXT NULL ,  PRIMARY KEY  (user_id) ,  UNIQUE INDEX  (email) )  ENGINE= InnoDB ; ,[object Object],[object Object],[object Object],[object Object],[object Object],CREATE TABLE Customer( user_id  INT NOT NULL AUTO_INCREMENT , email  VARCHAR(80) NOT NULL , display_name  VARCHAR(50) NOT NULL , password  CHAR(41) NOT NULL ,  PRIMARY KEY  (user_id) ,  UNIQUE INDEX  (email) )  ENGINE = InnoDB ; CREATE TABLE  CustomerInfo ( user_id  INT NOT NULL , first_name  VARCHAR(25) NOT NULL , last_name  VARCHAR(25) NOT NULL , address  VARCHAR(80) NOT NULL , city  VARCHAR(30) NOT NULL , province  CHAR(2) NOT NULL , postcode  CHAR(7) NOT NULL ,  interests  TEXT NULL ,  bio  TEXT  NULL ,  signature   TEXT  NULL ,  skills   TEXT  NULL , PRIMARY KEY  (user_id) ,  FULLTEXT KEY  (interests, skills) )  ENGINE = MyISAM ;
Vertical partitioning ,[object Object],@Entity public class Customer {    int userid; String email;   String password; @OneToOne(fetch=LAZY) CustomerInfo info; } @Entity public class CustomerInfo {  int userid; String name; String interests; @OneToOne(mappedBy= &quot;CustomerInfo&quot;) Customer customer; }
Scalability: Sharding - Application Partitioning ,[object Object],[object Object],Cust_id 1-999 Cust_id 1000-1999 Cust_id 2000-2999 Sharding Architecture Web/App Servers
Know what SQL is executed  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
MySQL Query  Analyser ,[object Object],[object Object],[object Object],[object Object],[object Object],Its  not just slow running  queries that are a problem, Sometimes its  SQL  that  executes a lot   that kills your system
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object]
Query Types – 1  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],q = em.createQuery(“select e from Employee e WHERE ” + “e.empId LIKE  '” + id + “'” ); q = em.createQuery(“select e from Employee e WHERE ” + “e.empId LIKE ' :id '”); q. setParameter (“ id ”,  id ); NOT GOOD GOOD
Query Types – 2  ,[object Object],[object Object],[object Object]
Flush Mode  ,[object Object],[object Object],[object Object],[object Object],[object Object],//Assume JTA transaction Order order = em.find(Order.class, orderNumber); em.persist(order); Query q = em.createNamedQuery(“findAllOrders”); q.setParameter(“id”, orderNumber); q.setFlushMode(FlushModeType.COMMIT) ; //Newly added order will NOT visible List list = q.getResultList();
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object]
Transactions ,[object Object],[object Object],[object Object],[object Object],[object Object]
Carol McDonald Java Architect

Weitere ähnliche Inhalte

Was ist angesagt?

ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
habib_786
 

Was ist angesagt? (20)

Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
Second Level Cache in JPA Explained
Second Level Cache in JPA ExplainedSecond Level Cache in JPA Explained
Second Level Cache in JPA Explained
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Hibernate
HibernateHibernate
Hibernate
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & Streams
 
Ajax
AjaxAjax
Ajax
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 

Ähnlich wie JPA Best Practices

Advanced Hibernate V2
Advanced Hibernate V2Advanced Hibernate V2
Advanced Hibernate V2
Haitham Raik
 
Entity Manager
Entity ManagerEntity Manager
Entity Manager
patinijava
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - Transactions
Dmitry Buzdin
 
Advanced Hibernate
Advanced HibernateAdvanced Hibernate
Advanced Hibernate
Haitham Raik
 

Ähnlich wie JPA Best Practices (20)

Ecom lec4 fall16_jpa
Ecom lec4 fall16_jpaEcom lec4 fall16_jpa
Ecom lec4 fall16_jpa
 
Jpa 2.1 Application Development
Jpa 2.1 Application DevelopmentJpa 2.1 Application Development
Jpa 2.1 Application Development
 
Advanced Hibernate V2
Advanced Hibernate V2Advanced Hibernate V2
Advanced Hibernate V2
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
 
Lerman Vvs14 Ef Tips And Tricks
Lerman Vvs14  Ef Tips And TricksLerman Vvs14  Ef Tips And Tricks
Lerman Vvs14 Ef Tips And Tricks
 
04 Data Access
04 Data Access04 Data Access
04 Data Access
 
JavaEE Spring Seam
JavaEE Spring SeamJavaEE Spring Seam
JavaEE Spring Seam
 
Vmware vSphere Api Best Practices
Vmware vSphere Api Best PracticesVmware vSphere Api Best Practices
Vmware vSphere Api Best Practices
 
Ejb3 Presentation
Ejb3 PresentationEjb3 Presentation
Ejb3 Presentation
 
Jpa
JpaJpa
Jpa
 
Entity Manager
Entity ManagerEntity Manager
Entity Manager
 
Ejb6
Ejb6Ejb6
Ejb6
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - Transactions
 
Advanced Hibernate
Advanced HibernateAdvanced Hibernate
Advanced Hibernate
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 

Mehr von Carol McDonald

Mehr von Carol McDonald (20)

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUs
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine Learning
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health Care
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep Learning
 
Spark graphx
Spark graphxSpark graphx
Spark graphx
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churn
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient Data
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka API
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision Trees
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming Data
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

JPA Best Practices

  • 1. Java Persistence API: Best Practices Carol McDonald Java Architect
  • 2.
  • 3.
  • 4. Catalog Java EE Application DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean
  • 5. EJB EntityManager Example @Stateless public class Catalog implements CatalogService { @PersistenceContext(unitName=”PetCatalogPu”) EntityManager em; @TransactionAttribute(NOT_SUPPORTED) public List<Item> getItems (int firstItem , int batchSize ) { Query q = em . createQuery (&quot; select i from Item as i &quot;); q. setMaxResults ( batchSize ); q. setFirstResult ( firstItem ); List<Item> items= q.getResultList(); return items; } }
  • 6. Catalog Spring JPA Application DB Registration Application Managed Bean JSF Components Spring Bean Entity Class Catalog Item ItemController Spring Framework
  • 7. Spring with JPA @Repository @Transactional public class CatalogDAO implements CatalogService { @PersistenceContext (unitName=&quot;PetCatalogPu&quot;) private EntityManager em; @Transactional(readOnly=true) public List<Item> getItems (int firstItem,int batchSize) { Query q = em. createQuery(&quot;select object(o) from Item as o&quot;); q.setMaxResults(batchSize); q.setFirstResult(firstItem); List<Item> items= q.getResultList(); return items; } Component Stereotype Spring transactions use aop
  • 8.
  • 9.
  • 10.
  • 11. Level1 and Level2 caches The terms “Java Virtual Machine” and “JVM” mean a Virtual Machine for the Java ™ Platform. Source:http://weblogs.java.net/blog/guruwons/archive/2006/09/understanding_t.html Persistence Context is a Level 1 cache Transaction Transaction Transaction Persistence Context (EntityManager) Persistence Context (EntityManager) Persistence Context (EntityManager) L2 Cache (Shared Cache) Entity managers for a specific PersistenceUnit on a given Java Virtual Machine (JVM ™ )
  • 12.
  • 13. Entity Lifecycle Illustrated – The Code @Stateless public ShoppingCartBean implements ShoppingCart { @PersistenceContext EntityManager entityManager; public OrderLine createOrderLine(Product product , Order order) { O rderLine orderLine = new OrderLine(order, product); entityManager.persist(orderLine); return (orderLine); } } New entity Managed entity Detached entity Persistence context
  • 14. Scope of Identity @Stateless public ShoppingCartBean implements ShoppingCart { @PersistenceContext EntityManager entityManager; public OrderLine createOrderLine( Product product,Order order) { O rderLine orderLine = new OrderLine(order, product); entityManager.persist(orderLine); OrderLine orderLine2 = entityManager.find (OrderLine, orderLine.getId()) ); ( orderLine == orderLine2 ) // TRUE return (orderLine); } } Persistence context Multiple retrievals of the same object return references to the same object instance
  • 15.
  • 16.
  • 17.
  • 18. Declarative Transaction Management Example TX_REQUIRED TX_REQUIRED TX_REQUIRED PC PC PC Shopping Cart Inventory Service Order Service Check Out 1. Update Inventory New Persistence Context Persistence Context Propagated Transaction Attributes 2. Create Order
  • 19. AuditServiceBean @Stateless public class AuditServiceBean implements AuditService { @PersistenceContext private EntityManager em; @TransactionAttribute(REQUIRES_NEW) public void logTransaction2(int id, String action) { LogRecord lr = new LogRecord(id, action); em.persist(lr); } NEW PC !
  • 20. Declarative Transaction Management Example 2 REQUIRED REQUIRED REQUIRES_NEW PC PC PC2 Shopping Cart Inventory Service Audit Service Check Out 1. Update Inventory New Persistence Context Persistence Context Propagated Transaction Attributes 2. log transaction NEW PC !
  • 21.
  • 22. Persistence Context Conversation with detached entity Persistence Context merge() transaction-scoped persistence context request response request response Conversation transaction-scoped persistence context
  • 23. Conversation with detached entity @Stateless public ShoppingCartBean implements ShoppingCart { @PersistenceContext EntityManager entityManager; public OrderLine createOrderLine(Product product,Order order) { OrderLine orderLine = new OrderLine(order, product); entityManager.persist (orderLine); return ( orderLine ); } public OrderLine updateOrderLine(OrderLine orderLine ){ OrderLine orderLine2 = entityManager.merge (orderLine) ); return orderLine2 ; } } Managed entity Detached entity Managed entity
  • 24.
  • 25. Persistence Context Conversation with Exented Persistence Context request response request response Conversation extended persistence context
  • 26. Extended Persistence Context @Stateful public class OrderMgr { //Specify that we want an EXTENDED @PersistenceContext (type=PersistenceContextType.EXTENDED) EntityManager em ; //Cached order private Order order ; //create and cache order public void createOrder(String itemId) { //order remains managed for the lifetime of the bean Order order = new Order(cust); em.persist( order ); } public void addLineItem (OrderLineItem li){ order. lineItems.add(li); } Managed entity Managed entity
  • 27. Extended Persistence Context @Stateful public class DeptMgr { @PersistenceContext (type=PersistenceContextType.EXTENDED) EntityManager em ; private Department dept; @TransactionAttribute(NOT_SUPPORTED) public void getDepartment(int deptId) { dept = em.find(Department.class,deptId); } @TransactionAttribute(NOT_SUPPORTED) public void addEmployee (int empId){ emp = em.find(Employee.class,empId); dept.getEmployees().add(emp); emp.setDepartment(dept); } @Remove @TransactionAttribute(REQUIRES_NEW) public void endUpdate(int deptId) { dept = em.find(Department.class,deptId); }
  • 28. Persistence Context- Transactional vs. Extended @Stateless public class OrderMgr implements OrderService { @PersistenceContext EntityManager em; public void addLineItem (OrderLineItem li){ // First, look up the order. Order order = em.find(Order.class, orderID); order.lineItems.add(li); } @Stateful public class OrderMgr implements OrderService { @PersistenceContext(type = PersistenceContextType. EXTENDED )) EntityManager em; // Order is cached Order order public void addLineItem (OrderLineItem li){ // No em.find invoked for the order object order.lineItems.add(li); } look up the order No em.find invoked Managed entity
  • 29.
  • 30.
  • 31. Concurrency and Persistence Context Object Identity only one manage entity in PC represents a row User 2 transaction User 1 transaction Persistence Context 1 Entity Manager Persistence Context 2 Entity Manager Data source same entity
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42. L2 cache shared across transactions and users Putting it all together User Session User Session User Session Persistence Context (EntityManager) Persistence Context (EntityManager) Persistence Context (EntityManager) L2 Cache (Shared Cache) Entity managers for a specific PersistenceUnit on a given Java Virtual Machine (JVM ™ ) (EntityManagerFactory)
  • 43.
  • 44. L2 Cache L2 Cache query that looks for a single object based on Id will go 1st to PC then to L2 cache, other queries go to database or query cache Shared entity User transaction 1 Persistence Context User transaction 2 Persistence Context Data source same entity not shared
  • 45.
  • 46.
  • 47.
  • 48. EclipseLink Caching Architecture EclipseLink caches Entities in L2, Hibernate does not EntityManager EntityManager Factory Server L1 Cache PC Cache L2 Shared Cache Cache Coordination JMS (MDB) RMI CORBA IIOP
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56. Example – Domain Model @Entity public class Employee { @Id private int id; private String firstName; private String lastName; @ManyToOne(fetch=LAZY) private Department dept; ... } @Entity public class Department { @Id private int id; private String name; @OneToMany(mappedBy = &quot;dept&quot;, fetch=LAZY) private Collection<Employee> emps = new ...; ... }
  • 57. Example – Managing Relationship public int addNewEmployee(...) { Employee e = new Employee(...); Department d = new Department(1, ...); e.setDepartment(d); //Reverse relationship is not set em.persist(e); em.persist(d); return d.getEmployees().size(); } INCORRECT
  • 58. Example – Managing Relationship public int addNewEmployee(...) { Employee e = new Employee(...); Department d = new Department(1, ...); e.setDepartment(d); d.getEmployees().add(e); em.persist(e); em.persist(d); return d.getEmployees().size(); } CORRECT
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65. Using Cascade @Entity public class Employee { @Id private int id; private String firstName; private String lastName; @ManyToOne( cascade=ALL , fetch=LAZY) private Department dept; ... } @Entity public class Department { @Id private int id; private String name; @OneToMany(mappedBy = &quot;dept&quot; cascade=ALL , fetch=LAZY) private Collection<Employee> emps = new ...; @OneToMany private Collection<DepartmentCode> codes; ... } Employee Department DepartmentCode cascade=ALL X
  • 66.
  • 67.
  • 68.
  • 69. Mapping Inheritance Hierarchies Employee --------------------------- int id String firstName String lastName Department dept PartTimeEmployee ------------------------ int rate FullTimeEmployee ----------------------- double salary
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84. Carol McDonald Java Architect