Enterprise Java v121030Java EE Transactions1. Enterprise Java v121030Java EE Transactions2 Goals Understand the basic concepts behind a transaction Be.

Slides:



Advertisements
Similar presentations
21 Copyright © 2005, Oracle. All rights reserved. Oracle Application Server 10g Transaction Support.
Advertisements

11 Copyright © 2005, Oracle. All rights reserved. Creating the Business Tier: Enterprise JavaBeans.
Transactions - Concurrent access & System failures - Properties of Transactions - Isolation Levels 4/13/2015Databases21.
Concurrency Control WXES 2103 Database. Content Concurrency Problems Concurrency Control Concurrency Control Approaches.
Chapter 16 Concurrency. Topics in this Chapter Three Concurrency Problems Locking Deadlock Serializability Isolation Levels Intent Locking Dropping ACID.
1 Lecture 11: Transactions: Concurrency. 2 Overview Transactions Concurrency Control Locking Transactions in SQL.
Transactions Celsina Bignoli Motivations Atomic operations –Group of operation that must all succeed or all fail Network or machine.
Transaction Processing Lecture ACID 2 phase commit.
Concurrency Control and Recovery In real life: users access the database concurrently, and systems crash. Concurrent access to the database also improves.
JBoss Seam: Contextual Components Jason Bechtel
Module 7 Security and Transactions. Security and Transactions Topics to be Covered: Security and the Enterprise Transactions.
Transaction Management and Concurrency Control
Java 2 – Enterprise Edition Kevin J. LaFata April 21, 2003 UM – St. Louis.
Version # Software Engineering Institute Carnegie Mellon University Pittsburgh, PA Sponsored by the U.S. Department of Defense © 1999 by Carnegie.
Enterprise Java Beans (EJB)
Database Administration Part 1 Chapter Six CSCI260 Database Applications.
J2EE Kenneth M. Anderson CSCI Web Technologies October 3, 2001.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
Faculty of Information Technology © Copyright UTS Faculty of Information Technology – TransactionsTransactions-1 Advanced Java Programming Transactions.
TRANSACTION PROCESSING TECHNIQUES BY SON NGUYEN VIJAY RAO.
1 IT420: Database Management and Organization Transactions 31 March 2006 Adina Crăiniceanu
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
1 The JNDI ENC and Injection Every EJB container that is deployed in an application server has its own personal internal registry called the Enterprise.
EJB. Component Characteristics An enterprise Bean typically contains business logic that operates on the enterprise’s data. An enterprise Bean’s instances.
1 ACID Transactions To understand how transactions work, we will revisit the TravelAgent EJB, the stateful session bean developed in Lecture 11 that encapsulates.
Enterprise Java Beans - (EJB)
© jGuru.com EJB Transactions. Transactions Simple Transaction –Transaction = more than one statement which must all succeed (or all fail) together.
Enterprise JavaBeans EJB Container Services. EJB container Enterprise JavaBeans are deployed in an EJB container within the application server EJB container.
EJB Container services Presentation by Arun Kalluri (04/02/2001)
September 16, 2010COMS W41561 COMS W4156: Advanced Software Engineering Prof. Gail Kaiser
Enterprise JavaBeans. What is EJB? l An EJB is a specialized, non-visual JavaBean that runs on a server. l EJB technology supports application development.
EJB Framework.  As we know, EJB is the center of the J2EE architecture that provides a sturdy framework for building enterprise applications. The major.
Message-Driven Beans and EJB Security Lesson 4B / Slide 1 of 37 J2EE Server Components Objectives In this lesson, you will learn about: Identify features.
Java Transaction API Sean C. Sullivan
J2EE Overview ver 1.0Page 1 © Wipro Technologies Talent Transformation J2EE Overview.
Transactions1 Unit of work on a database. Transactions2 Transactions, concept Logical unit of work on the database –Examples Transfer money from bank.
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
Concurrency and Transaction Processing. Concurrency models 1. Pessimistic –avoids conflicts by acquiring locks on data that is being read, so no other.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 136 Database Systems I SQL Modifications and Transactions.
Transaction Services in Component Frameworks Bruce Kessler Comp250CBS March 2, 2004.
1 Transactions Michael Brockway Sajjad Shami CG0165: Advanced Applications Development in Java Northumbria University School of Computing, Engineering.
Chapter 16 Concurrency. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.16-2 Topics in this Chapter Three Concurrency Problems Locking Deadlock.
Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel.
Giovanni Chierico | May 2012 | Дубна Data Concurrency, Consistency and Integrity.
EJB Overview: Constraint Types and Enforcement in JBoss Elissa Newman Fluid Meeting 6/3/04.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
SQLintersection Understanding Transaction Isolation Levels Randy Knight Wednesday, 3:45-5:00.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_JDBC_MySQL 1 Transations.
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
JPA Transactions
v110912Java Persistence: EntityManager2 Overview Earlier versions of EJB Specification defined the persistence layer –javax.ejb.EntityBean Java EE 5 moved.
1 Advanced Database Concepts Transaction Management and Concurrency Control.
Java Programming: Advanced Topics 1 Enterprise JavaBeans Chapter 14.
Copyright © 2002 ProsoftTraining. All rights reserved. Enterprise JavaBeans.
红杉树(中国)信息技术有限公司公司 地址:杭州市天目山路 176 号西湖数源软件园 11 号楼 3 层 电话: (86) Transaction & JAVA Fondy Wang 12/7/07.
IS-907 Java EE Introduction to JPA. Java Persistence API A framework for using relational databases in Java programs mapping between tables and classes,
17 Copyright © 2004, Oracle. All rights reserved. Integrating J2EE Components.
Chapter 13 Managing Transactions and Concurrency Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition.
Locks, Blocks & Isolation Oh My!. About Me Keith Tate Data Professional for over 14 Years MCITP in both DBA and Dev tracks
Transactions and Security. Contents  Transactions  Transaction Support in EJB  Security  Security Support in EJB.
JTA | Developer Conference JBoss Transactions Ivo Studenský JBoss QA Engineer, Jiří Pechanec JBoss QE Supervisor, Red Hat Sep 10th, 2009.
Transaction Management and Concurrency Control
On transactions, and Atomic Operations
Batches, Transactions, & Errors
Objectives In this lesson, you will learn to:
On transactions, and Atomic Operations
Batches, Transactions, & Errors
Transactions and Concurrency
Objectives In this lesson, you will learn about:
Presentation transcript:

Enterprise Java v121030Java EE Transactions1

Enterprise Java v121030Java EE Transactions2 Goals Understand the basic concepts behind a transaction Be able to define transaction scope and properties within the EJB Tier

Enterprise Java v121030Java EE Transactions3 Objectives Transaction Overview Transaction Scope Class Annotations and XML Descriptors SessionSynchronization Transaction Propagation Isolation Issues Database Locks Isolation Levels Programmatic and Optimistic Locking Bean Managed Transactions Exceptions and Transactions

Enterprise Java v121030Java EE Transactions4 Transactions Unit of work that accesses one or more shared resources (usually databases) –set of one or more activities related to each other –must be completed together or not at all –cohesion of unit is normally mission critical –examples ATM –withdraw from one source, deposit to another Order System –locate item, charge account, schedule shipment Medical System –identify medical state, dispense prescription

Enterprise Java v121030Java EE Transactions5 Transaction ACID Properties Atomic –Transaction must execute completely or not at all Consistent –Data in database is always in a consistent state (makes sense) –Constraints (primary keys, referential integrity, etc.) Isolated –Transaction executes without interference Durable –Changes are not lost if the system crashes

Enterprise Java v121030Java EE Transactions6 EJB Transaction Support Declarative –transaction management controlled through deployment descriptor Programmatic –direct programming calls –transaction management code mixed with business code change in transactional behavior requires change in business code

Enterprise Java v121030Java EE Transactions7 Transaction Scope javax.ejb.TransactionAttributeType ** MANDATORY –tx must be active before calling ** REQUIRED –tx will be created if not active ** REQUIRES_NEW –new tx will created, no matter what SUPPORTS –will join active transaction, but won't create one NOT_SUPPORTED –won't join active transaction and won't create one NEVER –tx must not be active when calling ** EJB3 strongly advises EntityManagers accessed within the scope of a JTA transaction; use one of these 3 for wrapping JPA implementations

Enterprise Java v121030Java EE Transactions8 Defining Transaction Attributes: Java Annotations Defining global default public class HotelRegistrationEJB implements HotelRegistrationRemote, HotelRegistrationLocal { Defining override for specific public class AgentReservationSessionEJB implements... public Booking commit() throws AgentReservationException {... }

Enterprise Java v121030Java EE Transactions9 Defining Transaction Attributes: ejb-jar.xml Defining a default for the EJB HotelRegistrationEJB... HotelRegistrationEJB * Required

Enterprise Java v121030Java EE Transactions10 Defining Transaction Attributes: ejb-jar.xml Defining a override for specific EJB method HotelReservationSessionEJB * NotSupported HotelReservationSessionEJB commit Required

Enterprise Java v121030Java EE Transactions11 Transaction Scope Determines whether –transaction must exist –transaction is started –transaction is adopted –transaction is ignored –transaction can't exist

Enterprise Java v121030Java EE Transactions12 Not Supported Invoked EJB Client Thread of Execution Client’s Transaction Context No Transaction Context Transaction is suspended during the method of the Invoked EJB; resumes when method complete Transaction scope is not propagated to Invoked EJB or anything it invokes

Enterprise Java v121030Java EE Transactions13 Supports Invoked EJB Client Joins the transaction context if invoked as part of a transaction (A) Does not require a transaction; can be invoked outside of a transaction context (B) Thread of Execution Client’s Transaction Context No Transaction Context (A) (B)

Enterprise Java v121030Java EE Transactions14 Required Invoked EJB Client Joins the transaction context if invoked as part of a transaction (A) Initiates its own transaction context of invoked outside of a transaction (B) Thread of Execution Client’s Transaction Context No Transaction Context (A) (B) EJB’s Transaction Context

Enterprise Java v121030Java EE Transactions15 RequiresNew Invoked EJB Client Initiates its own transaction context whether called within am existing transaction context (A) or outside of a transaction context (B) Initiated transaction completes prior to returning to caller Thread of Execution Client’s Transaction Context No Transaction Context (A) (B) EJB’s Transaction Context

Enterprise Java v121030Java EE Transactions16 Mandatory Invoked EJB Client Joins the transaction context if invoked as part of a transaction (A) Throws a Transaction Exception if not called within a transaction context (B) (TransactionRequiredException for Remote Clients; TransactionRequiredLocalException for Local Clients) Thread of Execution Client’s Transaction Context No Transaction Context (A) (B) Transaction Exception

Enterprise Java v121030Java EE Transactions17 Never Invoked EJB Client Throws a Transaction Exception if called within a transaction context (A) (RemoteException to Remote Clients; EJBException to Local Clients) Must be invoked outside of a transaction context (B) Thread of Execution Client’s Transaction Context No Transaction Context (A) (B) Transaction Exception

Enterprise Java v121030Java EE Transactions18 Scenario: Transaction Scope Client Creates 9 Valid and 1 Invalid Reservation HotelReservationSessionRemote session = //jndi.lookup for(int i=0; i<9; i++) { session.createReservation(person, startTime, endTime); } //now create a bad one session.createReservation(person, endTime, startTime); Client requests to EJB to complete all Reservations try { session.commit(); } catch (InvalidParameterException ex) {... } HotelRegistrationRemote reservationist = //jndi.lookup List mine = reservationist.getReservationsForPerson(person, 0, 100); if (mine.size() == 0) { log.info("all reservations were rolled back for: " + key); } else { log.info("" + mine.size() + " reservations were not rolled back for: " + key); }

Enterprise Java v121030Java EE Transactions19 Scenario: One Propogated Transaction Calling EJB public class AgentReservationSessionEJB implements... public Booking commit() throws AgentReservationException { /* for loop */ reservationist.createReservation( p.getPerson(), p.getStartDate(), p.getEndDate()); } Called EJB Requires a Tx; willing to public class HotelRegistrationEJB implements... { public Reservation createReservation(...) throws HotelReservationException { if (startDate == null) { throw new InvalidParameterException(...); }

Enterprise Java v121030Java EE Transactions20 Sample Result This one was specifically configured with REQUIRED -*** testBadCreates:RequiredSessionEJB *** -got expected exception:ejava.examples.txhotel.bl.InvalidParameterException: start date after end date -all reservations were rolled back for: RequiredSessionEJB This one is one took the defaults -*** testBadCreates:HotelReservationSessionEJB *** -got expected exception:ejava.examples.txhotel.bl.InvalidParameterException: start date after end date -all reservations were rolled back for: HotelReservationSessionEJB

Enterprise Java v121030Java EE Transactions21 Scenario: New Transactions Calling EJB public class AgentReservationSessionEJB implements... public Booking commit() throws AgentReservationException { /* for loop */ reservationist.createReservation( p.getPerson(), p.getStartDate(), p.getEndDate()); } Called EJB Requires a Tx; willing to public class HotelRegistrationEJB implements... { public Reservation createReservation(...) throws HotelReservationException { if (startDate == null) { throw new InvalidParameterException(...); }

Enterprise Java v121030Java EE Transactions22 Scenario: One Propogated Transaction Configured with REQUIRES_NEW -*** testBadCreates:RequiresNewSessionEJB *** -got expected exception:ejava.examples.txhotel.bl.InvalidParameterException: start date after end date -9 reservations were not rolled back for: RequiresNewSessionEJB

Enterprise Java v121030Java EE Transactions23 Transaction Propogation

Enterprise Java v121030Java EE Transactions24 Persistence ContextTransaction Propogation Tx-scoped Entity Manager called outside of Tx –creates transaction on entry –creates a new tx-scoped persistence context –commits transaction and detaches entities on exit Tx-scoped Entity Manager called with active Tx –creates new tx-scoped persistence context if needed –uses existing persistence context if present i.e., persistence context passed from EJB to EJB within Tx Exception thrown if persistence context passed to Stateful Session Bean using extended entity manager Extended persistence context from Stateful Session Bean is passed to tx- scoped Entity Managers when Stateless Session Bean called –Stateful Session Beans may only share extended persistence contexts with Stateful Session Beans injected by the container Persistence Contexts do not cross Tx scope boundaries

Enterprise Java v121030Java EE Transactions25 SessionSynchronization Stateful Session Bean –contain client state similar in concept to HttpSession –state may be tx-sensitive –may receive transaction lifecycle events unlike HttpSession

Enterprise Java v121030Java EE Transactions26 public class HotelReservationSessionEJB implements HotelReservationSessionLocal, HotelReservationSessionRemote, javax.ejb.SessionSynchronization { public void afterBegin() { log.debug("*** Transaction Started ***"); } public void beforeCompletion() throws EJBException, RemoteException { log.debug("*** Transaction about to complete ***"); } public void afterCompletion(boolean status) { log.debug("*** Transaction Completed:" + status + " ***"); }

Enterprise Java v121030Java EE Transactions27 SessionSynchronization [HotelReservationSessionEJB] *** HotelReservationSessionEJB *** [HotelReservationSessionEJB] [HotelReservationSessionEJB] reservationist=RequiresNewEJB [HotelReservationSessionEJB] *** Transaction Started *** [HotelReservationSessionImpl] ************ creating 10 reservations *** [HotelReservationSessionEJB] *** Transaction about to complete *** [HotelReservationSessionEJB] *** Transaction Completed:true *** [HotelReservationSessionEJB] *** HotelReservationSessionEJB closing *** [HotelReservationSessionEJB] *** HotelReservationSessionEJB *** [HotelReservationSessionEJB] [HotelReservationSessionEJB] reservationist=HotelRegistrationEJB [HotelReservationSessionEJB] *** Transaction Started *** [HotelReservationSessionImpl] ************ creating 10 reservations *** [HotelRegistrationEJB] error creating reservation, rolling back transaction:start date after end date [HotelReservationSessionEJB] *** Transaction Completed:false *** [HotelReservationSessionEJB] *** HotelReservationSessionEJB closing ***

Enterprise Java v121030Java EE Transactions28 Transaction Isolation What happens when two or more transactions attempt to access the same data –Dirty Reads first transaction reads uncommitted changes from a second transaction that may eventually be rolled back –Repeatable Reads data guaranteed to be the same if read multiple times during the same transaction; implemented with locks or snapshots –Phantom Reads first transaction sees new rows added by second transaction

Enterprise Java v121030Java EE Transactions29 Database Locks How do you prevent overlapping transactions from viewing the other’s data –Read Lock data is prevented from changing while transaction in progress –Write Lock prevents other transactions from modifying the data permits dirty reads by other transactions –Exclusive Write Lock prevents other transactions from reading and modifying data prevents dirty reads

Enterprise Java v121030Java EE Transactions30 Transaction Isolation Levels Read Uncommitted can read data being modified by another transaction allows dirty, non-repeatable, and phantom reads Read Committed cannot read data being modified by another transaction allows non-repeatable and phantom reads; prevents dirty reads Repeatable Read cannot change data being read by another transaction allows phantom reads; prevents dirty and non-repeatable reads Serializable transactions can neither read or write same data

Enterprise Java v121030Java EE Transactions31 Locking Programmatic Locking –EntityManager.lock(object, LockModeType) LockModeType.READ LockModeType.WRITE –Constrains system to work sequentially on locked resources –Bottleneck –Vendors not required to support field supplied Optimistic Locking –Permits parallel processing of information –Assumes that conflicts rarely occur –Error correction occurs after conflict detected

Enterprise Java v121030Java EE Transactions32 Optimistic Locking Problem Client requests a Reservation Reservation reservation = new Reservation(...); em.persist(em); return reservation; A second client request obtains another copy return em.find(Reservation.class, id); The first client makes a change reservation.setStartDate(...) The second client makes a change reservation.setCost(...) The first client change is made on server em.merge(reservation) The second client change is made on server em.merge(reservation) Impact, the first client change is lost

Enterprise Java v121030Java EE Transactions33 javax.persistence Support Add a version field to the class and annotate public class Reservation implements Serializable private long private long version; private String confirmation; private Date startDate; private Date endDate; private Person person; Or provide metadata about existing field <entity class="ejava.examples.txhotel.bo.Reservation"

Enterprise Java v121030Java EE Transactions34 javax.persistence Support EntityManager will check whether update is using current version of class or will throw exception reservation.setVersion(version - 1); start.add(Calendar.DAY_OF_YEAR, 1); reservation.setStartDate(start.getTime()); log.debug("trying to change:" + reservation); try { reservation = em.merge(reservation); fail("failed to check version"); } catch (OptimisticLockException ex) { log.debug("caught expected exception:" + ex); }

Enterprise Java v121030Java EE Transactions35 Manual Transaction Control Java Transaction Service (JTS) –Java implementation of the OMG Object Transaction Service (OTS) –robust, complete, and complicated Java Transaction API (JTA) –simplified –javax.transaction –Java EE registers manual JTA interface in JNDI »java:comp/UserTransaction »also available from SessionContext.getUserTransaction(); –example »UserTransaction tx = //... »tx.begin(); »do something »tx.commit(); //or rollback –can be used by Session Beans »public class...

Enterprise Java v121030Java EE Transactions36 Bean Managed Transactions Stateless Session Beans –transactions must begin and end within the scope of a single method Stateful Session Beans –transaction may begin and end in separate methods

Enterprise Java v121030Java EE Transactions37 Exceptions and Transactions Default –Checked Exceptions do not impact transactions –System Exceptions automatically rollback transaction sub-classes of RuntimeException –EJBException –NullPointerException –RemoteException Customization –Checked exceptions can be configured to rollback transaction java.sql.SQLException true

Enterprise Java v121030Java EE Transactions38 Summary –ACID Transactions Automic, Consistent, Isolated, Durable –Transaction Scope Mandatory, Required, RequiresNew, Supports, NotSupported, Never –Class Annotations and XML Descriptors Is the Java code that independent of the transaction configuration? Are there portability issues from environment to environment –SessionSynchronization

Enterprise Java v121030Java EE Transactions39 Summary (cont.) Isolation Issues –dirty reads –repeatable reads –phantom reads Database Locks –Read Locks –Write Locks –Exclusive Write Locks Isolation Levels –Read Uncommitted –Read Committed –Repeatable Read –Serializable

Enterprise Java v121030Java EE Transactions40 Summary (cont.) Locking –Programmatic –Optimistic Bean Managed Transactions –JTA UserTransaction Exceptions and Transactions

Enterprise Java v121030Java EE Transactions41 References “Enterprise JavaBeans 3.0, 5 th Edition”; Burke & Monsen-Haefel; ISBN X; O'Reilly