SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternShahriar Hyder
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean ArchitectureMattia Battiston
 
Java Serialization
Java SerializationJava Serialization
Java Serializationimypraz
 
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
 
PySpark in practice slides
PySpark in practice slidesPySpark in practice slides
PySpark in practice slidesDat Tran
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mappingAbhilash M A
 
Programming in Spark using PySpark
Programming in Spark using PySpark      Programming in Spark using PySpark
Programming in Spark using PySpark Mostafa
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentationJohn Slick
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
The Parquet Format and Performance Optimization Opportunities
The Parquet Format and Performance Optimization OpportunitiesThe Parquet Format and Performance Optimization Opportunities
The Parquet Format and Performance Optimization OpportunitiesDatabricks
 
Garbage collection
Garbage collectionGarbage collection
Garbage collectionSomya Bagai
 

Tendances (20)

introduction of Java beans
introduction of Java beansintroduction of Java beans
introduction of Java beans
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Spark SQL
Spark SQLSpark SQL
Spark SQL
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
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
 
PySpark in practice slides
PySpark in practice slidesPySpark in practice slides
PySpark in practice slides
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
 
Programming in Spark using PySpark
Programming in Spark using PySpark      Programming in Spark using PySpark
Programming in Spark using PySpark
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
The Parquet Format and Performance Optimization Opportunities
The Parquet Format and Performance Optimization OpportunitiesThe Parquet Format and Performance Optimization Opportunities
The Parquet Format and Performance Optimization Opportunities
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Dernier (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

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