SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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 examplesecosio GmbH
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
Spring Boot Persistence Best Practices - How to effectively shape the @OneToM...
Spring Boot Persistence Best Practices - How to effectively shape the @OneToM...Spring Boot Persistence Best Practices - How to effectively shape the @OneToM...
Spring Boot Persistence Best Practices - How to effectively shape the @OneToM...Anghel Leonard
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications JavaAntoine Rey
 
Spring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaSpring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaEdureka!
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginnersRahul Jain
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 

What's hot (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
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Jpa
JpaJpa
Jpa
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Second Level Cache in JPA Explained
Second Level Cache in JPA ExplainedSecond Level Cache in JPA Explained
Second Level Cache in JPA Explained
 
Spring Boot Persistence Best Practices - How to effectively shape the @OneToM...
Spring Boot Persistence Best Practices - How to effectively shape the @OneToM...Spring Boot Persistence Best Practices - How to effectively shape the @OneToM...
Spring Boot Persistence Best Practices - How to effectively shape the @OneToM...
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
 
Spring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaSpring Boot Interview Questions | Edureka
Spring Boot Interview Questions | Edureka
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 

Similar to 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
 

More from Carol McDonald

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUsCarol McDonald
 
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...Carol McDonald
 
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-DBCarol McDonald
 
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...Carol McDonald
 
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 LearningCarol McDonald
 
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-DBCarol McDonald
 
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...Carol McDonald
 
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...Carol McDonald
 
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...Carol McDonald
 
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 CareCarol McDonald
 
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 LearningCarol McDonald
 
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...Carol McDonald
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Carol McDonald
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churnCarol McDonald
 
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 1Carol McDonald
 
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 DataCarol McDonald
 
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 APICarol McDonald
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesCarol McDonald
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataCarol McDonald
 

More from 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
 

Recently uploaded

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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 CVKhem
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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 WorkerThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Recently uploaded (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

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