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

Tendances (20)

Codemotion Madrid 2023 - Testcontainers y Spring Boot
Codemotion Madrid 2023 - Testcontainers y Spring BootCodemotion Madrid 2023 - Testcontainers y Spring Boot
Codemotion Madrid 2023 - Testcontainers y Spring Boot
 
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
 
Universal metrics with Apache Beam
Universal metrics with Apache BeamUniversal metrics with Apache Beam
Universal metrics with Apache Beam
 
Introduction to Solidity and Smart Contract Development (9).pptx
Introduction to Solidity and Smart Contract Development (9).pptxIntroduction to Solidity and Smart Contract Development (9).pptx
Introduction to Solidity and Smart Contract Development (9).pptx
 
Monitoring and Orchestration of your Microservices Landscape with Kafka and Z...
Monitoring and Orchestration of your Microservices Landscape with Kafka and Z...Monitoring and Orchestration of your Microservices Landscape with Kafka and Z...
Monitoring and Orchestration of your Microservices Landscape with Kafka and Z...
 
Solidity
SoliditySolidity
Solidity
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
 
Erc721 token & crypto kitties analysis
Erc721 token & crypto kitties analysisErc721 token & crypto kitties analysis
Erc721 token & crypto kitties analysis
 
"The Intersection of architecture and implementation", Mark Richards
"The Intersection of architecture and implementation", Mark Richards"The Intersection of architecture and implementation", Mark Richards
"The Intersection of architecture and implementation", Mark Richards
 
C# Game Server
C# Game ServerC# Game Server
C# Game Server
 
20180711 Metamask
20180711 Metamask 20180711 Metamask
20180711 Metamask
 
Akka-intro-training-public.pdf
Akka-intro-training-public.pdfAkka-intro-training-public.pdf
Akka-intro-training-public.pdf
 
가상화된 코드를 분석해보자
가상화된 코드를 분석해보자가상화된 코드를 분석해보자
가상화된 코드를 분석해보자
 
Astricon 2016 - Scaling ARI and Production
Astricon 2016 - Scaling ARI and ProductionAstricon 2016 - Scaling ARI and Production
Astricon 2016 - Scaling ARI and Production
 
Dhcp authentication using certificates
Dhcp authentication using certificatesDhcp authentication using certificates
Dhcp authentication using certificates
 
Write smart contract with solidity on Ethereum
Write smart contract with solidity on EthereumWrite smart contract with solidity on Ethereum
Write smart contract with solidity on Ethereum
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams
 
Efficient Schemas in Motion with Kafka and Schema Registry
Efficient Schemas in Motion with Kafka and Schema RegistryEfficient Schemas in Motion with Kafka and Schema Registry
Efficient Schemas in Motion with Kafka and Schema Registry
 
Apache Kafka as Event Streaming Platform for Microservice Architectures
Apache Kafka as Event Streaming Platform for Microservice ArchitecturesApache Kafka as Event Streaming Platform for Microservice Architectures
Apache Kafka as Event Streaming Platform for Microservice Architectures
 
[En] IPVS for Docker Containers
[En] IPVS for Docker Containers[En] IPVS for Docker Containers
[En] IPVS for Docker Containers
 

Similaire à Jpa buenas practicas

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

Similaire à Jpa buenas practicas (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
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

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...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Jpa buenas practicas

  • 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

Notes de l'éditeur

  1. To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don&apos;t need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance&apos;s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don&apos;t need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  2. To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don&apos;t need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance&apos;s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don&apos;t need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  3. Here is how you could do this with a stateless session bean. We inject reference to a container managed EntityManager using the persistence context annotation. We create a new order and the entity has the state of new. We call persist, making this a managed entity. because it is a stateless session bean it is by default using container managed transactions , when this transaction commits , the order is made persistent in the database. When we return the serialiable orderline entity it is a detached entity
  4. Here is how you could do this with a stateless session bean. We inject reference to a container managed EntityManager using the persistence context annotation. We create a new order and the entity has the state of new. We call persist, making this a managed entity. because it is a stateless session bean it is by default using container managed transactions , when this transaction commits , the order is made persistent in the database. When we return the serialiable orderline entity it is a detached entity
  5. In a transaction-scoped container managed entity manager (common case in a Java EE environment), the JTA transaction propagation is the same as the persistence context resource propagation. In other words, container-managed transaction-scoped entity managers retrieved within a given JTA transaction all share the same persistence context.
  6. In a transaction-scoped container managed entity manager (common case in a Java EE environment), the JTA transaction propagation is the same as the persistence context resource propagation. In other words, container-managed transaction-scoped entity managers retrieved within a given JTA transaction all share the same persistence context.
  7. Here is how you could do this with a stateless session bean. We inject reference to a container managed EntityManager using the persistence context annotation. We create a new order and the entity has the state of new. We call persist, making this a managed entity. because it is a stateless session bean it is by default using container managed transactions , when this transaction commits , the order is made persistent in the database. When we return the serialiable orderline entity it is a detached entity
  8. A persistence context can be either transaction scoped or extended scope. A transaction scope pc is one that is bound to a jta it starts and ends at transaction boundaries. At the end of the transaction the entities become detached. An extended pc spans multiple transactios, and it exists from the time the em is created until it is closed. An extended pc can be useful in web apps when you have conversations that span multiple requests. So the em can remain open between requests and you can close the em when done. Components like Stateful session can hold references to managed instances. It avoids flushing the database between requests and then re-finding entities so in some cases can improve performance. The type of pc is defined when you create the entity manager Persistence contexts may live as long as a transaction and be closed when a transaction completes. This is called a transaction-scoped persistence context . When the transaction completes, the transaction-scoped persistence context will be destroyed and all managed entity object instances will become detached. Persistence contexts may also be configured to live longer than a transaction. This is called an extended persistence context . Entity object instances that are attached to an extended context remain managed even after a transaction is complete. This feature is extremely useful in situations where you want to have a conversation with your database but not keep a long-running transaction
  9. In this example the sb looks up an order, adds a line items. The stateless session bean does the workflow with a lookup and merge in each operation as needed, whereas the stateful session bean does the same by caching the references.
  10. Optimistic locking permits all users to read and attempt to update the same data, concurrently. It does not prevent others from changing the same data, but it does guarantee the database will not be updated based on stale data. Pessimistic locking is the most restrictive form of locking but guarantees no changes are performed on the data during your transaction. The database physically locks the row upon a select (SELECT . . . FOR UPDATE [NOWAIT]) and prevents others from altering that row. This reassurance comes at a cost as pessimistic locks cannot be held across transactions and only one user can access the underlying data. Pessimistic locking should be used carefully as it limits concurrent access to the data and may cause deadlocks.
  11. The spec mendates that a persistence application operates at “read committed” level that is no dirty reads (or uncommitted data) is read.
  12. The spec mendates that a persistence application operates at “read committed” level that is no dirty reads (or uncommitted data) is read.
  13. The spec mendates that a persistence application operates at “read committed” level that is no dirty reads (or uncommitted data) is read.
  14. An application might want to share entity state across various persistence contexts This is the domain of second level (L2) cache If caching is enabled, entities not found in persistence context, will be loaded from L2 cache, if found JPA does not specify support of a second level cache However, most of the persistence providers provide in-built or integrated support for second level cache(s) Basic support for second level cache in GlassFish-TopLink Essentials is turned on by default No extra configuration is needed
  15. The spec mendates that a persistence application operates at “read committed” level that is no dirty reads (or uncommitted data) is read.
  16. Lazy loading and JPA With JPA many-to-one and many-to-many relationships lazy load by default , meaning they will be loaded when the entity in the relationship is accessed. Lazy loading is usually good, but if you need to access all of the &amp;quot;many&amp;quot; objects in a relationship, it will cause n+1 selects where n is the number of &amp;quot;many&amp;quot; objects. You can change the relationship to be loaded eagerly as follows : public class Employee{ @OneToMany(mappedBy = &amp;quot;employee&amp;quot;, fetch = FetchType.EAGER) private Collection&lt;Address&gt; addresses; ..... } However you should be careful with eager loading which could cause SELECT statements that fetch too much data. It can cause a Cartesian product if you eagerly load entities with several related collections. If you want to temporarily override the LAZY fetch type, you could use Fetch Join. For example this query would eagerly load the employee addresses: @NamedQueries({ @NamedQuery(name=&amp;quot;getItEarly&amp;quot;, query=&amp;quot;SELECT e FROM Employee e JOIN FETCH e.addresses&amp;quot;)}) public class Employee{ ..... }
  17. Lazy loading and JPA With JPA many-to-one and many-to-many relationships lazy load by default , meaning they will be loaded when the entity in the relationship is accessed. Lazy loading is usually good, but if you need to access all of the &amp;quot;many&amp;quot; objects in a relationship, it will cause n+1 selects where n is the number of &amp;quot;many&amp;quot; objects. You can change the relationship to be loaded eagerly as follows : However you should be careful with eager loading which could cause SELECT statements that fetch too much data. It can cause a Cartesian product if you eagerly load entities with several related collections. If you want to temporarily override the LAZY fetch type, you could use Fetch Join. For example this query would eagerly load the employee addresses: Cartiesian product is the set of all possible ordered pairs
  18. Lazy loading and JPA With JPA many-to-one and many-to-many relationships lazy load by default , meaning they will be loaded when the entity in the relationship is accessed. Lazy loading is usually good, but if you need to access all of the &amp;quot;many&amp;quot; objects in a relationship, it will cause n+1 selects where n is the number of &amp;quot;many&amp;quot; objects. You can change the relationship to be loaded eagerly as follows : public class Employee{ @OneToMany(mappedBy = &amp;quot;employee&amp;quot;, fetch = FetchType.EAGER) private Collection&lt;Address&gt; addresses; ..... } However you should be careful with eager loading which could cause SELECT statements that fetch too much data. It can cause a Cartesian product if you eagerly load entities with several related collections. If you want to temporarily override the LAZY fetch type, you could use Fetch Join. For example this query would eagerly load the employee addresses: @NamedQueries({ @NamedQuery(name=&amp;quot;getItEarly&amp;quot;, query=&amp;quot;SELECT e FROM Employee e JOIN FETCH e.addresses&amp;quot;)}) public class Employee{ ..... }
  19. In a normalized database, each fact is represented once and only once. Conversely, in a denormalized database, information is duplicated, or stored in multiple places. People who ask for help with performance issues are frequently advised to normalize their schemas, especially if the workload is write-heavy. This is often good advice. It works well for the following reasons: Normalized updates are usually faster than denormalized updates. When the data is well normalized, there&apos;s little or no duplicated data, so there&apos;s less data to change. Normalized tables are usually smaller, so they fit better in memory and perform better. The lack of redundant data means there&apos;s less need for DISTINCT or GROUP BY queries when retrieving lists of values. Consider the preceding example: it&apos;s impossible to get a distinct list of departments from the denormalized schema without DISTINCT or GROUP BY, but if DEPARTMENT is a separate table, it&apos;s a trivial query. The drawbacks of a normalized schema usually have to do with retrieval. Any nontrivial query on a well-normalized schema will probably require at least one join, and perhaps several. This is not only expensive, but it can make some indexing strategies impossible. For example, normalizing may place columns in different tables that would benefit from belonging to the same index.
  20. single table means that all of those classes are being stored in the same table and all we need is a a discriminator column in that table . So the disc column tells what type. This leads to some wastage of space, if you have a rate then you don&apos;t have a salary . But it does make for quick querying because you can find through a single table scan all of the objects of a type.
  21. joined hierarchy , great for storage a little more expensive for querying
  22. finally table per class says that every concrete class gets its own table and it will repeat all the inherited state in that table.
  23. An example of vertical partitioning might be a table that contains a number of very wide text or BLOB columns that aren&apos;t addressed often being broken into two tables that has the most referenced columns in one table and the seldom-referenced text or BLOB data in another. • limit number of columns per table • split large, infrequently used columns into a separate one-to-one table By removing the VARCHAR column from the design, you actually get a reduction in query response time. Beyond partitioning, this speaks to the effect wide tables can have on queries and why you should always ensure that all columns defined to a table are actually needed.
  24. You need to understand the SQL queries your application makes and evaluate their performance To Know how your query is executed by MySQL, you can harness the MySQL slow query log and use EXPLAIN. Basically you want to make your queries access less data: is your application retrieving more data than it needs, are queries accessing too many rows or columns? is MySQL analyzing more rows than it needs? Indexes are a good way to reduce data access. When you precede a SELECT statement with the keyword EXPLAIN, MySQL displays information from the optimizer about the query execution plan. That is, MySQL explains how it would process the SELECT, including information about how tables are joined and in which order. With the help of EXPLAIN, you can see where you should add indexes to tables to get a faster SELECT that uses indexes to find rows. You can also use EXPLAIN to check whether the optimizer joins the tables in an optimal order. Developers should run EXPLAIN on all SELECT statements that their code is executing against the database. This ensures that missing indexes are picked up early in the development process and gives developers insight into how the MySQL optimizer has chosen to execute the query.
  25. MySQL Query Analyzer The MySQL Query Analyzer is designed to save time and effort in finding and fixing problem queries. It gives DBAs a convenient window, with instant updates and easy-to-read graphics, The analyzer can do simple things such as tell you how long a recent query took and how the optimizer handled it (the results of EXPLAIN statements). But it can also give historical information such as how the current runs of a query compare to earlier runs. Most of all, the analyzer will speed up development and deployment because sites will use it in conjunction with performance testing and the emulation of user activity to find out where the choke points are in the application and how they can expect it to perform after deployment. The MySQL Query Analyzer saves time and effort in finding and fixing problem queries by providing: Aggregated view into query execution counts, run time, result sets across all MySQL servers with no dependence on MySQL logs or SHOW PROCESSLIST Sortable views by all monitored statisticsSearchable and sortable queries by query type, content, server, database, date/time, interval range, and &amp;quot;when first seen&amp;quot;Historical and real-time analysis of all queries across all serversDrill downs into sampled query execution statistics, fully qualified with variable substitutions, and EXPLAIN results The new MySQL Query Analyzer was added into the MySQL Enterprise Monitor and it packs a lot of punch for those wanting to ensure their systems are free of bad running SQL code. let me tell you the two things I particularly like about it from a DBA perspective: 1. It&apos;s Global: If you have a number of servers, you&apos;ll love what Query Analyzer does for you. Even Oracle and other DB vendors only provide single-server views of bad SQL that runs across their servers. Query Analyzer bubbles to the top the worst SQL across all your servers – which is a much more efficient way to work. No more wondering what servers you need to spend your time on or which have the worst code. 2. It&apos;s Smart: Believe it or not, sometimes it&apos;s not slow-running SQL that kills your system – it&apos;s SQL that executes way more times than you think it is. You really couldn&apos;t see this well before Query Analyzer, but now you can. One customer already shaved double-digits off their response time by finding queries that were running more much than they should have been. And that&apos;s just one area Query Analyzer looks at; there&apos;s much more intelligence there too, along with other stats you can&apos;t get from the general server utilities.