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 (" select i from Item as i "); 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="PetCatalogPu") private EntityManager em; @Transactional(readOnly=true) public List<Item> getItems (int firstItem,int batchSize) { Query q = em. createQuery("select object(o) from Item as o"); 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 !
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 = "dept", 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 = "dept" 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
To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance'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'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.
To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance'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'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.
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
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
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.
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.
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
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
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.
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.
The spec mendates that a persistence application operates at “read committed” level that is no dirty reads (or uncommitted data) is read.
The spec mendates that a persistence application operates at “read committed” level that is no dirty reads (or uncommitted data) is read.
The spec mendates that a persistence application operates at “read committed” level that is no dirty reads (or uncommitted data) is read.
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
The spec mendates that a persistence application operates at “read committed” level that is no dirty reads (or uncommitted data) is read.
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 &quot;many&quot; objects in a relationship, it will cause n+1 selects where n is the number of &quot;many&quot; objects. You can change the relationship to be loaded eagerly as follows : public class Employee{ @OneToMany(mappedBy = &quot;employee&quot;, fetch = FetchType.EAGER) private Collection<Address> 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=&quot;getItEarly&quot;, query=&quot;SELECT e FROM Employee e JOIN FETCH e.addresses&quot;)}) public class Employee{ ..... }
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 &quot;many&quot; objects in a relationship, it will cause n+1 selects where n is the number of &quot;many&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
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 &quot;many&quot; objects in a relationship, it will cause n+1 selects where n is the number of &quot;many&quot; objects. You can change the relationship to be loaded eagerly as follows : public class Employee{ @OneToMany(mappedBy = &quot;employee&quot;, fetch = FetchType.EAGER) private Collection<Address> 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=&quot;getItEarly&quot;, query=&quot;SELECT e FROM Employee e JOIN FETCH e.addresses&quot;)}) public class Employee{ ..... }
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's little or no duplicated data, so there'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's less need for DISTINCT or GROUP BY queries when retrieving lists of values. Consider the preceding example: it'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'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.
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'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.
joined hierarchy , great for storage a little more expensive for querying
finally table per class says that every concrete class gets its own table and it will repeat all the inherited state in that table.
An example of vertical partitioning might be a table that contains a number of very wide text or BLOB columns that aren'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.
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.
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 &quot;when first seen&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's Global: If you have a number of servers, you'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's Smart: Believe it or not, sometimes it's not slow-running SQL that kills your system – it's SQL that executes way more times than you think it is. You really couldn'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's just one area Query Analyzer looks at; there's much more intelligence there too, along with other stats you can't get from the general server utilities.