P. 1
2.16_20.TD09_JPA_best_practices2

2.16_20.TD09_JPA_best_practices2

|Views: 267|Likes:
Publicado porosman uygar köse

More info:

Published by: osman uygar köse on Jan 19, 2011
Direitos Autorais:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

11/12/2011

pdf

text

original

Sections

  • Agenda
  • Catalog Java EE Application
  • Catalog Spring JPA Application
  • Container vs Application Managed
  • Level1 and Level2 caches
  • Entity Lifecycle
  • Entity Lifecycle Illustrated – The Code
  • Scope of Identity
  • Persistence Context
  • Declarative Transaction Management Example
  • AuditServiceBean
  • Declarative Transaction Management Example 2
  • Persistence Provider PC Transaction Features
  • Conversation with detached entity
  • Types of Persistence Context
  • Conversation with Exented Persistence Context
  • Persistence Context Micro Benchmark
  • Concurrency and Persistence Context
  • Optimistic versus Pessimistic Concurrency
  • Preventing Parallel Updates – 1
  • Preventing Stale Data
  • Preventing Parallel Updates – 2
  • L2 cache shared across transactions and users
  • Second-level Cache
  • L2 Cache
  • JPA 2.0 Shared Cache API
  • EclipseLink Caching Architecture
  • EclipseLink Extensions - L2 Caching
  • EclipseLink Mapping Extensions Type=
  • OpenJPA L2 Caching
  • Maintaining Relationship
  • Example – Domain Model
  • Navigating Relationships
  • Using Cascade
  • Database design Basic foundation of performance
  • Normalization
  • Mapping Inheritance Hierarchies
  • Single Table Per Class
  • Joined Subclass
  • Table Per Class
  • vertical partitioning
  • Vertical partitioning
  • Scalability: Sharding - Application Partitioning
  • Know what SQL is executed
  • MySQL Query Analyser
  • Query Types – 1
  • Query Types – 2
  • Flush Mode
  • Transactions

Java Persistence API

:
Best Practices
Carol McDonald Java Architect
1

Agenda

>Entity Manager >Persistence Context >Entities >Schema & Queries >Transaction
2

EntityManager API for managing entities
EntityManager

set of entities managed by Entity Manager

Servlets EJBs Java app

persist() remove() refresh() merge() find() createQuery() contains() flush()

createNamedQuery()Persistence

Context

3

Catalog Java EE Application
Registration Application
Managed Bean

Entity Class

Item

DB

ManagedBean

Catalog Session Bean

JSF Components

4

q. return items.S t a t e l e s s S e s s io n B e a n A n n o t a t io n EJB EntityManager Example D e p e n d e n c y In j e c t io n @Stateless public class Catalog implements CatalogService { @PersistenceContext(unitName=”PetCatalogPu”) EntityManager em.createQuery ("select i from Item as i"). @TransactionAttribute(NOT_SUPPORTED) public List<Item> getItems(int firstItem. q.getResultList().setFirstResult(firstItem). List<Item> items= q. } } 5 .setMaxResults(batchSize). int batchSize) { Query q = em.

Catalog Spring JPA Application Registration Application Managed Bean Entity Class Item DB ItemController Catalog Spring Bean JSF Components Spring Framework 6 .

setMaxResults(batchSize). q. @Transactional(readOnly=true) public List<Item> getItems(int firstItem. List<Item> items= q. q. return items.Spring with JPA Component Stereotype Spring transactions use aop @Repository @Transactional public class CatalogDAO implements CatalogService { @PersistenceContext(unitName="PetCatalogPu") private EntityManager em.getResultList().int batchSize) { Query q = em. } 7 .setFirstResult(firstItem).createQuery("select object(o) from Item as o").

createEntityManagerFactory() > RESOURCE_LOCAL transaction – not propagated > Need to explicitly close entity manager 8 . Spring Bean.Container vs Application Managed Container managed entity managers (EJB. Seam component) • Injected into application • Automatically closed • JTA transaction – propagated Application managed entity managers > Used outside of the JavaEE 5 platform > Need to be explicitly created ● Persistence.

Agenda >Entity Manager >Persistence Context >Entities >Queries >Transaction 9 .

Persistence Context • Persistence context acts as a first level cache for entities • Two types of persistence context > Transaction scoped > Extended scoped set of entities managed by Entity Manager EntityManager persist() remove() refresh() merge() find() createQuery() contains() flush() persistence context createNamedQuery()Persistence Context 10 .

html 11 .java.Level1 and Level2 caches 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™) The terms “Java Virtual Machine” and “JVM” mean a Virtual Machine for the Java™ Platform. Source:http://weblogs.net/blog/guruwons/ archive/2006/09/understanding_t.

Entity Lifecycle new() New Entity Detached Entity Updates PC ends persist() Persistence Context Managed Entity Managed Managed Entity Entity Merge() find() Transaction commit Guaranteed Scope of Object Identity only one manage entity in PC represents a row remove() Removed Entity 12 .

return (orderLine). product).Entity Lifecycle Illustrated – The Code @Stateless public ShoppingCartBean implements ShoppingCart { New entity @PersistenceContext EntityManager entityManager. entityManager.persist(orderLine). Persisten context public OrderLine createOrderLine(Product product . Order order) { OrderLine orderLine = new OrderLine(order. Managed entity } Detached entity } 13 .

orderLine. (orderLine == orderLine2) // TRUE return (orderLine). entityManager. } Multiple retrievals of the same object return references to the same object instance } 14 . product).Order order) OrderLine orderLine = new OrderLine(order.Scope of Identity @Stateless public ShoppingCartBean implements ShoppingCart { @PersistenceContext EntityManager entityManager.persist(orderLine).find(OrderLine.getId())). Persistence context public OrderLine createOrderLine(Product product. OrderLine orderLine2 =entityManager.

Persistence Context • Two types of persistence context • Transaction scoped > Used in stateless components > Typically begins/ends at request entry/exit points respectively • Extended scoped persistence context 15 .

updateInventory(Product p) } } Persistence context 16 . public void checkout(Item i. @EJB OrderService ord. Product p) { inv. ord.Persistence Context Propagation @Stateless public class ShoppingCartBean implements ShoppingCart { @EJB InventoryService inv.createOrder(item).

} } @Stateless public class InventoryServiceBean implements InventoryService { @PersistenceContext EntityManager em2..merge(p). .. public void updateInventory(Product p) { Product product = em2.Persistence Context Propagation @Stateless public class OrderServiceBean implements OrderService { @PersistenceContext EntityManager em1.persist(new Order(item)). public void createOrder(Item item) { em1. } 17 .

Create Order Order Service PC TX_REQUIRED 18 .Declarative Transaction Management Example Check Out New Persistence Context Persistence Context Propagated Shopping Cart PC 1. Update Inventory Inventory Service PC TX_REQUIRED TX_REQUIRED Transaction Attributes 2.

NEW PC ! @TransactionAttribute(REQUIRES_NEW) public void logTransaction2(int id. String action) { LogRecord lr = new LogRecord(id.persist(lr). em. } 19 . action).AuditServiceBean @Stateless public class AuditServiceBean implements AuditService { @PersistenceContext private EntityManager em.

Update Inventory Inventory Service REQUIRED PC Transaction Attributes 2. log transaction Audit Service PC2 REQUIRES_NEW NEW PC ! 20 .Declarative Transaction Management Example 2 Check Out New Persistence Context Persistence Context Propagated Shopping Cart REQUIRED PC 1.

UPDATE and DELETE statements • Minimizes database interactions • EntityManager flush SQL prior to commit 21 .Persistence Provider PC Transaction Features • Attribute-level change tracking • Only the minimal updates are sent to the database • Orders INSERT.

Conversation with detached entity Conversation request response transaction-scoped persistence context Persistence Context Managed Entity Managed Managed Entity Entity request Detached Entity Detached Entity response transaction-scoped persistence context Persistence Context Managed Entity Managed Managed Entity Entity merge() 22 .

Managed entity return (orderLine). } Detached entity public OrderLine updateOrderLine(OrderLine orderLine){ OrderLine orderLine2 =entityManager. return orderLine2. public OrderLine createOrderLine(Product product.persist(orderLine).merge(orderLine)).Conversation with detached entity @Stateless public ShoppingCartBean implements ShoppingCart { @PersistenceContext EntityManager entityManager.Order order) { OrderLine orderLine = new OrderLine(order. } } Managed entity 23 . entityManager. product).

Types of Persistence Context • Persistence Context > lifetime maybe transaction-scoped or extended • Transaction-scoped persistence context • Extended persistence context > spans multiple transactions 24 .

Conversation with Exented Persistence Context Conversation request response request response extended persistence context Persistence Context Managed Entity Managed Entity Managed Entity 25 .

add(li).lineItems.EXTENDED) EntityManager em. } Managed entity 26 .persist(order). Managed entity } public void addLineItem(OrderLineItem li){ order.Extended Persistence Context @Stateful public class OrderMgr { //Specify that we want an EXTENDED @PersistenceContext(type=PersistenceContextType. 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).

class.empId).find(Employee.EXTENDED) EntityManager em. @TransactionAttribute(NOT_SUPPORTED) public void getDepartment(int deptId) { dept = em. emp. } @TransactionAttribute(NOT_SUPPORTED) public void addEmployee(int empId){ emp = em. } 27 .setDepartment(dept). } @Remove @TransactionAttribute(REQUIRES_NEW) public void endUpdate(int deptId) { dept = em.class.deptId).Extended Persistence Context @Stateful public class DeptMgr { @PersistenceContext(type=PersistenceContextType.find(Department. dept.find(Department.deptId). private Department dept.add(emp).class.getEmployees().

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); }

look up the order

@Stateful
public class

OrderMgr

implements OrderService {

@PersistenceContext(type = PersistenceContextType.EXTENDED)) EntityManager em; Managed entity // Order is cached Order order public void addLineItem(OrderLineItem li){ No em.find invoked // No em.find invoked for the order object order.lineItems.add(li); }
28

Persistence Context Micro Benchmark
• Micro benchmark with lots of lookups • Persistence context is caching entities
120% 100% 80% 60% 40% 20% 0%

Extended Transactional

tx/sec
Source: Internal benchmarks
29

SEAM Conversations
@Name("shopper") @Scope(CONVERSATION) public class BookingManager { @In EntityManager entityManager; private Booking booking; @Begin public void selectHotel(Hotel selectedHotel){ hotel = em.merge(selectedHotel); } @End public void confirm() { em.persist(booking); } }

SEAM injected

SEAM conversation
30

Concurrency and Persistence Context
User 1 transaction Persistence Context 1 same entity
Entity Manager Entity Manager

User 2 transaction Persistence Context 2

Object Identity only one manage entity in PC represents a row

Data source
31

.0 (vendor specific). .0 > Suitable when application has many parallel updates 32 . FOR UPDATE [NOWAIT]) > Pros—Simpler application code > Cons—Database locks ● limits concurrent access to the data = scalability ● May cause deadlocks ● Not in JPA 1.Optimistic versus Pessimistic Concurrency • Optimistic Concurrency > Pros—No database locks held > Cons—Requires a version attribute in schema ● user or app must refresh and retry failed updates > Suitable when application has few parallel updates • Pessimistic Concurrency > Lock the row when data is read in ● database locks the row upon a select ● (SELECT . supported in JPA 2.

Integer.Preventing Parallel Updates use @Version for optimistic locking public class Employee { @ID int id.. long. Can be int. Timestamp Used by persistence manager . Short. merged or acquiring a write lock OptimisticLockException if mismatch Not used by the application! 33 ... @Version int version. short.. . Long. Results in following SQL “UPDATE Employee SET . version = version + 1 WHERE id = ? AND version = readVersion” Version Updated when transaction commits..

tx1. //Joe's employee id is 5 //e1.commit().version == 1 e1 = findPartTimeEmp(5).version == 2 in db //Joe's rate is $11 //Joe's current rate is $9 if(e1. //Joe's current rate is $9 tx2. //Joe's employee id is 5 //e1. //e1. Time //e1.Preventing Parallel Updates – 1 tx1.begin(). //Joe's rate is $14 //OptimisticLockException 34 .raise(2).version == 1 e1 = findPartTimeEmp(5).begin().getRate() < 10) e1. e1.commit().raise(5).version == 1 in db? tx2.

35 .0 • Perform read or write locks on entities • Prevents non-repeatable reads in JPA entityManager. perform a version check on entity before commit OptimisticLockException if mismatch perform a version check on entity OptimisticLockException if mismatch and increment version before commit entityManager. WRITE). READ).Preventing Stale Data JPA 1.lock( entity.lock( entity.

version in db tx2.getDepartment().setName(“MarketEngrg”). Time //Check d1. tx2. tx1. em. //e1 gets the raise he does //not deserve //Transaction rolls back 36 . //d1's original name is //”Engrg” d1. d1 = findDepartment(dId).begin().commit().Preventing Stale Data tx1. e1 = findEmp(eId).begin(). if(d1's name is “Engrg”) e1.lock(d1. READ).raiseByTenPercent().commit(). d1 = e1.

begin(). e1 = findEmp(eId).flush(). WRITE).commit().raiseByTenPercent(). 37 .getDepartment(). //tx rolls back Time tx2.begin(). if(d1's name is “Engrg”) e1. tx2.Preventing Parallel Updates – 2 Write lock prevents parallel updates tx1. //version++ for d1 em.setName(“MarketEngrg”).commit(). em. d1 = e1. d1 = findDepartment(dId). //d1's original name is //”Engrg” d1.lock(d1. tx1.

0 only supported optimistic locking. JPA 2.0 also supports pessimistic locks • JPA 2. FOR UPDATE ) 38 . . .0 Locks • JPA1.JPA 2.0 LockMode values : > > > > • Multiple places to specify lock OPTIMISTIC (= READ) OPTIMISTIC_FORCE_INCREMENT (= WRITE) PESSIMISTIC database locks the row PESSIMISTIC_FORCE_INCREMENT (SELECT .

setBalance(balance .100).PESSIMISTIC). acct. Lock after read. // Decide to withdraw $100 (already locked) int balance = acct. Locks longer.find(Account.100).class. acct.class. // Decide to withdraw $100 so lock it for update em. PESSIMISTIC).0 Locking //Read then lock: Account acct = em.getBalance().getBalance(). could cause bottlenecks.lock(acct. acctId). risk stale. could cause OptimisticLock Exception //Read and lock: Account acct = em. int balance = acct.setBalance(balance .JPA 2.find(Account. deadlock 39 . acctId.

JPA 2. get optimistic lock exception ● // read then lock and refresh Account acct = em. PESSIMISTIC).refresh(acct.0 Locking Trade-offs: ●lock earlier : risk bad scalability. acctId).find(Account.lock and refresh em.setBalance(balance .class. acct.getBalance(). deadlock ●Lock later : risk stale data for update. “right” approach depends on requirements 40 . // Decide to withdraw $100 .100). int balance = acct.

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) (EntityManagerFactory) Entity managers for a specific PersistenceUnit on a given Java Virtual Machine (JVM™) 41 .

EclipseLink. entities not found in persistence context.Hibernate.0 has basic cache operations > Most persistence providers-. OpenJPA .Second-level Cache • L2 Cache shares entity state across various persistence contexts > If caching is enabled.0 does not specify L2 support > Java Persistence API 2. provide second-level cache(s) 42 . will be loaded from L2 cache.. if found • Best for read-mostly classes • L2 Cache is Vendor specific > Java Persistence API 1..

other queries go to database or query cache L2 Cache Data source 43 .L2 Cache User transaction 1 same entity not shared Persistence Context Persistence Context User transaction 2 Shared entity Entity Entity query that looks for a single object based on Id will go 1st to PC then to L2 cache.

or pessimistic lock) ●Bad scalability for frequent or concurrently updated entities 44 .L2 Caching • Pros: > avoids database access for already loaded entities ●faster for reading frequently accessed unmodified entities • Cons > memory consumption for large amount of objects > Stale data for updated objects > Concurrency for write (optimistic lock exception.

refresh policy to minimize lock failures • Configure Query cache > Useful for queries that are run frequently with the same parameters.L2 Caching • Configure L2 caching for entities that are > read often > modified infrequently > Not critical if stale • protect any data that can be concurrently modified with a locking strategy > Must handle optimistic lock failures on flush/commit > configure expiration. for not modified tables 45 .

// invalidates object in the IdentityMap public void evict(Class class.JPA 2. // invalidates the class in the IdentityMap. public void evict(Class class). Object pk). public void evictAll().0 Shared Cache API • entity cache shared across persistence unit > Accessible from EntityManagerFactory • Supports only very basic cache operations > Can be extended by vendors public class Cache { //checks if object is in IdentityMap public boolean contains(Class class. Object pk). // Invalidates all classes in the IdentityMap } 46 .

EclipseLink Caching Architecture EntityManager EntityManager Factory EclipseLink caches Entities in L2. Hibernate does not L1 Cache PC Cache Server L2 Shared Cache Cache Coordination JMS (MDB) RMI CORBA IIOP 47 .

INVALIDATE. RMI-IIOP. size. RMI. type.EclipseLink Extensions .refreshing > Coordination (cluster-messaging) ● Messaging: JMS. coordination. invalidation. NONE 48 . expiration. … ● Mode: SYNC. SYNC+NEW.L2 Caching • Default: Entities read are L2 cached • Cache Configuration by Entity type or Persistence Unit > You can disable L2 cache • Configuration Parameters > Cache isolation.

expiry=600000. expiry.EclipseLink Mapping Extensions Type= @Entity @Table(name="EMPLOYEE") @Cache ( type=CacheType.isolated. refresh. } Full: objects never flushed unless deleted or evicted weak: object will be garbage collected if not referenced =true disables L2 cache @Cache ● type. disableHits=true.. isolated=false.. coordinationType=INVALIDATE_CHANGED_OBJECTS ) public class Employee implements Serializable { . coordination ● Cache usage and refresh query hints 49 . alwaysRefresh=true. cache usage.WEAK. size.

Hibernate L2 Cache • Hibernate L2 cache is not configured by default • Hibernate L2 does not cache Entities. Hibernate caches Id and state • Hibernate L2 cache is pluggable > EHCache. disk clustered clustered Read-only Yes Yes Yes Yes Yes Read-write Yes Yes Transactional 50 . SwarmCacheProvider (JVM) > JBoss TreeCache Cluster > Can plug in others like Terracotta Cache Concurrency Strategy Cache EHCache OSCache SwarmCache JBoss Cache Type memory. OSCache. disk memory.

.configurationResourceName=/name_of_configuration_resource @Entity @Cache(usage = CacheConcurrencyStrategy.optional configuration file parameter --> not configured by default net. } Cache Concurrency Strategy must be supported by cache provider 51 .sf.. .ehcache.Hibernate L2 Cache <!-.NONSTRICT_READ_WRITE) public Class Country { private String name.

} 52 .OpenJPA L2 Caching • OpenJPA L2 caches object data and JPQL query • • • • results Updated when data is loaded from database and after changes are successfully committed For cluster caches are notified when changes are made Can plug in implementations. such as Tangosol’s Coherence product several cache eviction strategies: > Time-to-live settings for cache instances @Entity @DataCache(timeout=5000) public class Person { ...

Agenda >Entity Manager >Persistence Context >Entities >Schema and Queries >Transaction 53 .

Maintaining Relationship • Application bears the responsibility of maintaining relationship between objects deptA.getEmployees().add(e3). Before Employee1 After Employee1 Department A Employee2 Department A Inconsistent! Department B Employee2 Department B Employee3 Employee3 54 .

fetch=LAZY) private Collection<Employee> emps = new .. . private String lastName.. . @OneToMany(mappedBy = "dept". } @Entity public class Department { @Id private int id.. @ManyToOne(fetch=LAZY) private Department dept.Example – Domain Model @Entity public class Employee { @Id private int id. private String name. } 55 .... private String firstName..

) { Employee e = new Employee(... e.persist(d). em.).. //Reverse relationship is not set em.. Department d = new Department(1.).persist(e)..getEmployees().. return d.setDepartment(d). } 56 .Example – Managing Relationship INCORRECT public int addNewEmployee(.size(). .

d..Example – Managing Relationship CORRECT public int addNewEmployee(..setDepartment(d).getEmployees(). Department d = new Department(1. return d.. .) { Employee e = new Employee(.persist(d). e.). em. } 57 .). em....persist(e).size().add(e).getEmployees().

Navigating Relationships Data fetching strategy • EAGER – immediate • LAZY – loaded only when needed • LAZY is good for large objects and/or with relationships with deep hierarchies 58 .

id.. } • Default FetchType is LAZY for 1:m and m:n relationships > benefits large objects and relationships with deep hierarchies • However for use cases where data is needed can cause n+1 selects • LAZY – N + 1 problem: SELECT d.. FROM Department d // 1 time SELECT e. FROM Employee e WHERE e. . .deptId = ? // N times 59 ...id. @OneToMany(mappedBy = "dept") private Collection<Employee> emps ...Lazy loading and JPA @Entity public class Department { @Id private int id. .

.. could load too much ! OR • Temporarily override the LAZY fetch type.. } 60 .employees")}) public class Department{ .Lazy loading and JPA @Entity public class Department { @Id private int id.... query="SELECT d FROM Department d JOIN FETCH d. use Join Fetch in a query: @NamedQueries({ @NamedQuery(name="getItEarly".. fetch=EAGER) private Collection<Employee> employees . @OneToMany(mappedBy = "dept". } Can cause Cartesian product • Relationship can be Loaded Eagerly > But if you have several related relationships.

logging.xml file:<property name="toplink.Lazy loading and JPA • Capture generated SQL > persistence.level" value="FINE"> • Test run use cases and examine the SQL statements > optimise the number of SQL statements executed! > only retrieve the data your application needs! • Lazy load large (eg BLOB) attributes and relationships that are not used often • Override to Eagerly load in use cases where needed 61 .

Navigating Relationships Detached Entity • Accessing a LAZY relationship from a detached entity > If not loaded . Causes an exception • Solutions: > Use JOIN FETCH > Or Set Fetch type to EAGER > Or Access the collection before entity is detached: d. Persistence Context Managed Entity 62 .size().getEmployees().

REMOVE. REFRESH > The default is do nothing • Avoid MERGE. limit the scope 63 .Navigating Relationships Data fetching strategy • Cascade specifies operations on relationships > ALL. PERSIST. MERGE. ALL with deep hierarchies > If want to do it.

} 64 .Using Cascade @Entity public class Employee { Employee @Id private int id.. @OneToMany private Collection<DepartmentCode> codes. private String name.. ... private String firstName. cascade=ALL @ManyToOne(cascade=ALL.. private String lastName. . fetch=LAZY) Department private Department dept. fetch=LAZY) private Collection<Employee> emps = new . @OneToMany(mappedBy = "dept" cascade=ALL. X } @Entity public class Department { DepartmentCode @Id private int id...

Agenda >Entity Manager >Persistence Context >Entities >Schema and Queries >Transaction 65 .

can  ve  t   gi beter peror ance f m > U se  sm al dat t as  l  a ypes  possi e as  bl > use  sm al  i ar key  possi e as  lprm y  as  bl > Veri   tton: tcalParii ●spltl ge.l m em or   l di  ess  y.Database design Basic foundation of performance • Sm alert es  l  abl use ess  sk.i r i ar  nfequenty  l used  um ns nt a  col i o  separ e  at one­o­ t one abl t e • U se  good ndexi i ng > I ndexes  Speed  Q uer up  ys > I ndexes  ow   sl dow n  pdat U es > I ndex  um ns r col fequenty  l used n  uer W her cl i Q y  e  ause 66 .

●there's less data to change. • However Normalized database causes joins for queries > Queries maybe slower > Normalize then maybe De-normalize frequently read columns and cache them 67 .Normalization • Normalization Eliminates redundant data > updates are usually faster.

Mapping Inheritance Hierarchies Employee --------------------------int id String firstName String lastName Department dept PartTimeEmployee ------------------------ FullTimeEmployee ----------------------- int rate double salary 68 .

double NULL. varchar(30) • Requires columns corresponding to subclasses' state to be null • Table can have too many columns > Larger tables= more data. varchar(255).Single Table Per Class Benefits @Inheritance(strategy=SINGLE_TABLE) • Simple EMPLOYEE --------------------------• No joins required ID Int PK. can have negative affects on performance – 69 . int FK. int NULL. > can be fast for Queries Drawbacks • Not normalized > Wastes space FIRSTNAME LASTNAME DEPT_ID RATE SALARY DISCRIM varchar(255).

SALARY double NULL hierarchies. RATE int NULL FULLTIMEEMPLOYEE ID int PK FK. polymorphic queries and relationships 70 . varchar(255). int FK. varchar(255). Benefits • Normalized database > Better for storage • Database view same as domain model • Easy to evolve domain model Drawbacks • Queries cause joins > Slower queries > Poor performance for deep PARTTIMEEMPLOYEE ID int PK FK.Joined Subclass @Inheritance(strategy=JOINED) EMPLOYEE ID FIRSTNAME LASTNAME DEPT_ID int PK.

LASTNAME varchar(255). RATE int NULL FULLTIMEEMPLOYEE ID FIRSTNAME LASTNAME DEPT_ID SALARY int PK.Table Per Class Benefits • No need for joins to read entities of same type > Faster reads @Inheritance(strategy=TABLE_PER_CLASS) Drawbacks • Not normalized > Wastes space PARTTIMEEMPLOYEE ID int PK. DEPT_ID int FK. FIRSTNAME varchar(255). varchar(255). varchar(255). double NULL • Polymorphic queries cause union (all employees) > Poor performance • This strategy is not mandatory 71 . int FK.

sH L   RO aV(T dA8  rR0N eC)U AN . TEXT data .E ek  X(si FTitl U nss LKt.oRT  d(  pe7N o )U sC L tHN cAO . EI Nn Go ID N Frequently referenced CTu( RAs EBt ALo TEm E e  Cr  iN NT u TAC sI UR eNNTE rTUOM _ L_E dO IN .eX  sT it  nsN t U eTL rE .R(d  Yu) P s RKe IEr MY_ A i .nRT  c(  pe2N r )U oC L vHN iAO .sH L   RO aV(T dA8  rR0N eC)U AN . EM Ny GI IS NA • limit number of columns per table • split large.oRT  d(  pe7N o )U sC L tHN cAO Less Frequently referenced.nR5N  aC)U lmH L aeAN s RO tV(T _A2  .sN   U sTL kE iX lT   .E )   ( UIe NNm IDa QEi UXl )EB  =.R(d  Yu) P s RKe IEr MY_ A i .eX  sT it  nsN t U eTL rE .oRO  r(T pd4  a 1N sC)U wAN H L . EI Nn Go ID N CTuI RAsn EBtf ALoo TEm  E e(  Cr  iN u T sI  eNN rTU _ L dO . RO  V(T eA8  mR0N aC)U iH L lAN .vertical partitioning CTu  RAs( EBt ALo TEm E e  Cr  iN NT u TAC sI UR eNNTE rTUOM _ L_E dO IN .tX  uT sr  ieN g U nTL aE .V(T  A3  cR0N iC)U tH L yAN  RO .nR5N  aC)U lmH L aeAN s RO tV(T _A2  .) TYrs Ee  )EM  =. RO  V(T eA8  mR0N aC)U iH L lAN .V(T  A3  cR0N iC)U tH L yAN  RO .sN   U sTL kE iX lT   . infrequently used columns into a separate table 72 ._A2   nR5N faC)U imH L reAN s RO tV(T .a RO  yV(T d_A5  inR0N saC)U pmH L leAN .tX  uT sr  ieN g U nTL aE .E )   ( UIe NNm IDa QEi UXl )EB  =.E  X bT i  oN  U TL .R(d  Yu) P s RKe IEr MY_ A i .a RO  yV(T d_A5  inR0N saC)U pmH L leAN .nRT  c(  pe2N r )U oC L vHN iAO ._A2   nR5N faC)U imH L reAN s RO tV(T .oRO  r(T pd4  a 1N sC)U wA L HN .E  X bT i  oN  U TL .

String name. String interests. infrequently used columns into a separate table . String email. @OneToOne(fetch=LAZY) CustomerInfo info. } @Entity public class CustomerInfo { int userid. String password. } 73 > split large.Vertical partitioning @Entity public class Customer { int userid. @OneToOne(mappedBy= "CustomerInfo") Customer customer.

Application Partitioning Web/App Servers Sharding Architecture Cust_id 1-999 Cust_id 1000-1999 Cust_id 2000-2999 > Sharding =Horizontal partitioning ●Split table by rows into partitions 74 .Scalability: Sharding .

xml file: <property name="toplink.level" value="FINE"> • Find and fix problem SQL: > Watch for slow Queries ● use the MySQL slow query log and use Explain – Can reveal problems such as a missing Indexes > Watch for Queries that execute too often to load needed data > Watch for loading more data than needed 75 .logging.Know what SQL is executed • Capture generated SQL: persistence.

Sometimes its SQL that executes a lot that kills your system • Historical and real-time analysis > query execution counts. run time 76 .MySQL Query Analyser Find and fix problem SQL: • how long a query took • results of EXPLAIN statements Its not just slow running queries that are a problem.

Agenda >Entities >Entity Manager >Persistence Context >Queries >Transaction 77 .

”). > Beware of SQL injection.empId LIKE ':id'”). q = em.xml • Dynamic query > Created dynamically by passing a query string to EntityManager • Query query = em.Query Types – 1 • Named query > Like findByXXXX() from EntityBeans > Compiled by persistence engine > Created either with @NamedQuery or externalized in orm. better to use with named q = em..createQuery(“select . parameters 78 .createQuery(“select e from Employee e WHERE ” GOOD + “e. q.createQuery(“select e from Employee NOT GOOD e WHERE ” + “e. id).setParameter(“id”..empId LIKE '” + id + “'”).

Query Types – 2 • Native query > Leverage the native database querying facilities > Not portable – ties queries to database 79 .

persist(order). //Newly added order will NOT visible List list = q.getResultList().COMMIT). q.Flush Mode • Controls whether the state of managed entities are synchronized before a query • Types of flush mode flush //Assume JTA transaction Order order = em.setFlushMode(FlushModeType.setParameter(“id”. default > COMMIT – flush only when a transaction commits > NEVER – need to invoke EntityManger. q. Query q = em. orderNumber).flush() to 80 .class. em.createNamedQuery(“findAllOrders”).find(Order. > AUTO – immediate. orderNumber).

Agenda >Entities >Entity Manager >Persistence Context >Queries >Transaction 81 .

Transactions • Do not perform expensive and unnecessary operations that are not part of a transaction on log > Hurt performance > Eg. logging – disk write are expensive. resource contention • Do not use transaction when browsing data > Create your own EntityManager as oppose to injected 82 .

Carol McDonald Java Architect 83 83 .

You're Reading a Free Preview

Descarregar
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->