Click here to load reader

W Ä ê Ì Ð ý Ò Ð Ájavaplant.tistory.com/attachment/[email protected] Ä _ ê Ì Ð ý Ò Ð Á 5SBOTBDUJPO D P I ç 5SBOTBDUJPO D X 2 ; ì 8"4 À ² D %JTUSJCVUFE 5SBOTBDUJPO

  • View
    213

  • Download
    0

Embed Size (px)

Text of W Ä ê Ì Ð ý Ò Ð Ájavaplant.tistory.com/attachment/[email protected] Ä _ ê Ì Ð ý...

Transaction , Transaction

WAS Distributed Transaction , Java

Transaction API , EJB Transaction

,

.

1. What is Transaction?

,

.

.

, A

B 1,000 .

.

1) A 1,000 .

2) B 1,000 .

A 1,000

, B 1,000

, 1,000

.

A 1,000 .

1), 2) .

.

,

Mission Critical

.

2. Transaction Attribute ACID

4 Atomicity,

Consistency, Isolation, Durability,

ACID .

ACID

.

1) Atomicity ()Database modifications must follow all or nothing.,

. step

, . ,

,

step ,

.

, step

rollback ,

.

,

All or Nothing .

2) Consistency ()States that only valid data will be written to the database

.

, , ,

, ,

, constraint ,

Consistency ,

, rollback

.

3) Isolation ()Multiple transactions occurring at the same time notimpact each other execution,

.

Tx A EMP ,

Tx A Tx B EMP

, Tx A

( Tx A )

.

1

8 www.bea.co.kr

Bea Enterprise Solution Technical News

4) Durability ()Ensure that any transaction committed to the databasewill not be lost.,

. ,

IO,

.

3. Distributed Transaction (Global Transaction)

1) Transaction in source code, ,

.

.

Begin Transaction ,

Transaction boundary .

// Do transaction Transaction

.

(SQL ..)

If(error) then roll back :

, rollback , .

, Prepare Transaction

, commit (Resource

Manager, DBMS ..) .

If(prepare transaction field) then rollbackElse Commit Transaction

Commit commit ,

rollback . End

Transaction .

,

Transaction

, .

J2EE EJB

EJB Container (CMT :

Container Managed Transaction Model)

, Handling

.

2) Distributed Transaction and XA

(Distributed transaction, or Global transaction

.) .

, Resource (RDBMS)

.

.

< 1. >

3

. AP, TM, RM.

Application

, AP Application, User

.

.

1

9www.bea.co.kr

Begin Transaction

// Do transaction

if(error) then roll back

Prepare Transaction.

if (prepare transaction failed) then rollback

else Commit Transaction

End Transaction

www.bea.co.kr10

1

Resource Manager

RM Resource Manager, Resource

. JAVA JDBC

, RM

DBMS Vendor JDBC

. RDBMS ,

RM Resource XA ISAM,

JMS .

Transaction Manager

TM Transaction Manager ,

. WAS

.

XA eXtended Architecture Open Group

, Global Transaction ,

RM TM .

,

.

.

Begin Transaction

Xid = get new transaction id

, Global

Transaction Id Xid .

, DB1 DB2 RM1 RM2

,

doTransaction(Xid,RM1)

doTransaction(Xid,RM2)

AP RM DB .

Xid RM

. ,

, error roll back

. ,

commitTransaction(Xid)

. TM RM . TM

RM1,RM2 commit RM

. RM Transaction

. (RDBMS

.

. ) ,

, TM RM Xid . TM RM

Xid commit

prepare .

Prepare TM RM commit

. prepare TM RM rollback

.

prepare commit

two phase commit (2pc) .

.

EndTransaction

, .

. ( XA ,

.

XA Spec, Transaction

.)

4. Transaction Isolation Level

Single User

Multi User ,

insert/update . ,

(Consistency) (Concurrency)

.

Begin Transaction

Xid = get new transation id

doTransaction(Xid,RM1)

doTransaction(Xid,RM2)

commitTransaction(Xid)

End Transaction

Bea Enterprise Solution Technical News

Data Consistency - ,

ACCESS ,

Data Concurrency - ,

ACCESS

(serially)

.

Transaction Isolation Level.

.

1) TX_A , TX_B

.

2) TX_A SELECT NAME FROM TABLE_A WHERE

ID=1 . ORIGIN

.

3) TX_B UPDATE TABLE_A SET NAME=

CHANGEDWHERE ID =1

4) TX_A SELECT NAME FROM TABLE_A

WHERE ID=1 .

5) TX_B COMMIT.

6) TX_A SELECT NAME FROM TABLE_A

WHERE ID=1 .

, 4) CHANGED ?

ORIGIN ? 6) CHANGED ORIGIN

?

(Isolation Level)

.

1) Preventable Phenomena

3

Preventable Phenomena ..

.

Dirty Read

, COMMIT

,

.

1) TX_A , SELECT NAME FROM TABLE_A

WHERE ID=1 ORIGIN .

2) TX_B UPDATE TABLE_A SET NAME=

CHANGEDWHERE ID =1

3) TX_A SELECT NAME FROM TABLE_A WHERE

ID=1 CHANGED .

2) UPDATE COMMIT

Dirty Read .

NonRepeatable Read (Fuzzy Read)

(update delete )

, COMMIT , COMMIT

.insert .

1) TX_A , SELECT NAME FROM TABLE_A

WHERE ID=1 ORIGIN .

2) TX_B UPDATE TABLE_A SET NAME=

CHANGEDWHERE ID =1

3) TX_A SELECT NAME FROM TABLE_A WHERE

ID=1 ORIGIN .

4) TX_B COMMIT

5) SELECT NAME FROM TABLE_A WHERE ID=1

CHAGNED .

Phantom Read

(Insert), COMMIT

, COMMIT .

(NonRepeatable read , NonRepeatable

update, delete Phantom Read insert

.)

1) TX_A , SELECT COUNT(*) FROM

TABLE_A WHERE GRP=1 10

.

2) TX_B INSERT INTO TABLE_A (ID,GRP)

VALUES(100,1);

3) TX_A SELECT COUNT(*) FROM TABLE_A

WHERE GRP=1 10 .

4) TX_B COMMIT

5) TX_A SELECT COUNT(*) FROM TABLE_A

WHERE GRP=1 11

1

11www.bea.co.kr

www.bea.co.kr12

1

2) Isolation Level

ANSI/ISO SQL (SQL92) 4 Isolation Level

.

.

3) How to setup Oracle and Java Isolation Level

Oracle DBMS Default

Read Commited , Oracle 9(),

Isolation Level Read commited, Serializable

.

Oracle Isolation Level SQL PLUS

LEVEL .

SET TRANSACTION ISOLATION LEVEL READ COMMITED;SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

JAVA Isolation Level

Isolation Level ,

.

Connection conn = DriverManager.getConnection(url, uid,

pwd);

conn.setTransactionIsolation(Connection.TRANSACTION_R

EAD_COMMITTED);

System.out.println(conn.getTransactionIsolation());

Isolation Level .

. Oracle

Oracle 8i Concepts Release 8.1.5 A67781-01

27 Data Concurrency and Consistency

.

5. Java transaction

, API

.

1) Java Transaction Model

Java Transaction API JTS(Java

Transaction Service) JTA (Java Transaction API)

.

JTS Transaction Manager Spec, JTA

Application, Application Server, Resource Manager

Interface Spec.

, Java Transaction Programming

JTA Interface JTS .

JTS Transaction Manager,

JTA Transaction Manager

.

, JTS

Transaction Manager Global Transaction

. WebLogic EJB , EJB

IBM Websphere EJB ,

.

, JTS Transaction Manager

CORBA OTS(Object Transaction Service)

Transaction Manager ,

Global Transaction

, OTS TM Transaction

.

Isolation Level Dirty Read

Read uncommitted Possible

Read committed Not Possible

Repeatable read Not Possible

Serializable Not Possible

NonRepeatable Read Phantom Read

Possible Possible

Possible Possible

Not Possible Possible

Not Possible Not Possible

Bea Enterprise Solution Technical News

Java Transaction API .

2) JTA

Java

. Java

API Java Transaction API(

JTA) . JTA TM, AP, RM

,

.

- User Transaction Interface

- Transaction Manager Interface

- Transaction Interface

- XAResource Interface

- Xid Interface

a) User Transaction Interface

javax.transaction.UserTransaction , AP TM

.

JTA User

Transaction Interface .(

Transaction Programming ,

Interface.)

EJB Server

UserTransaction utx = ctx.getUserTransaction();

// start Transaction

utx.begin();

// do transaction

:

utx.commit();

. ( EJB

Transaction Model TX_BEAN_MANAGED

.-Bean Managed Transaction)

b) Transaction Manager Interface

javax.transaction.TransactionManager interface, TM

Application Server .

(boudary) .

Transaction Context

, Thread

. , Thread Transaction

Global Transaction( ) .

Transaction Manager Interface

.

Transaction Context , Transaction

Context Transaction object encapsulation

. Transaction

Context reference ,

null .

Transaction Manager Transaction

,

.

Starting a Transaction

. , Transaction object

Transaction Context Thread Binding.

Completing a Transaction

TransactionManager.commit/rollback ,

1

13www.bea.co.kr

commit Thread (commit).

, Thread Transaction Context

null .

Suspending and Resuming Transaction

calling Thread Transaction suspend

, resume . Transaction ,

suspend , suspend (SQL)

Transaction .

c) Transaction Interface

Transaction Interface ,

Transaction . ,

, Resource ,

commit rollback .

Transaction , Transaction

Resource( RDBMS etc..) List Transaction object

. (transaction.enlistResouce)

Transaction object Resource list

. TM Transaction RM

Control ( commit, rollback )

.

, Transaction Equality Check Hash

code , synchronization .

JTA Spec .

d) XAResource Interface

TM RM . X/OPEN XA Spec

Resource Manager Implementation Java

.

Resource, XAResource Interface

, Resource local transaction begin,

commit, prepare . Resource

dependent , XA Interface Implementation

Class JDBC Driver vendor

.

XAResource Interface

.

XADataSource xaDS;

XAConnection xaCon;

XAResource xaRes;

Xid xid;

Connection conn;

Statement stmt;

int ret;

xaDS = getDataSource(); // vendor

xaCon = xaDS.getXAConnection(jdbc_user,

jdbc_password);

xaRes = xaCon.getXAResource();

con = xaCon.getConnection();

stmt = conn.createStatement();

// create new global transaction id

xid = new

MYXid(formatId,globalTransactionId,branchQualifier);

try{

xaRes.start(xid,XAResource.TMNOFLAGS); // start

transaction

stmt.executeUpdate(sql);

xaRes.end(xid,XAResource.TMSUCESS); // end

transaction

ret = xaRes.prepare(xid); // prepare

if(ret == XAResource.XA_OK) xaRes.commit(xid,false); //

commit

}catch(Exception e){

}finally{

stmt.close();

conn.close();

xaCon.close();

, Resource,

ID, xid ,

. XA Interface

Oracle WebLogic XA Interface

.

1

14 www.bea.co.kr

Bea Enterprise Solution Technical News

e) Xid Interface

Xid global transaction

ID Java Interface. X/Open

XID structure , transaction

format ID, global transaction ID, branch qualifier

.

3) JTS

4) JTA Support in the Application Server

, JTA/JTS Java

Application Server

.

( , Application Server

,

.

.)

TM : Transaction Manager

Application, Application Server ,

Transaction .

Application Application Server Connection

Transaction , Application Server

Transaction Manager Transaction

, Transaction Manager Resource vendor

(eg. SAP, Oracle, Message Queue etc..) Resource

Adapter , Resource (eg. ERP, RDBMS

etc.) , Transaction .

Resource Adapter vendor , JDBC

Driver Package Resource Adapter

. Resource Adapter ,

4 . ResourceFactory,

Transactional Resource, Connection, XAResouce .

ResourceFactory Transactional Resource

. RDMS XADataSource .

Transactional Resource Resource

Connection(XAConnection) , Resource

Resource Manager Interface ,

Application Connection (DB Connection)

Transaction Manager XAResource Interface

. .

Application Server Transaction Manager, Java

Application . Application Server

Transaction Manager XAResource, ,

Java Application Connection .

Application Server , Resource

Transactional Resource(XAConnection) .

1. Java Client TX_REQUIRED

EJB CALL . Java Client

Transaction , Transaction

EJB . Application Server

1

15www.bea.co.kr

Transaction Manager Global Transaction

. TransactionManager.begin

2. Transaction , Java Application

DB Connection .

3. Application Server JDBC (resource

adapter) , XADataSource (Resource

Factory) .

4. XADataSource , XAConnection(Transactional

Resource) . (getTransactionalResource)

5. XAConnection, XAResource, Connection .

6. Application server , XAResource

Transaction (enlistResource),

XAResource Interface , Resource

Transaction . (start)

7. Application server XAConnection

DBConnection Java Application .

(getConnection/returnConnection)

8. Java Application Connection

Transaction , Connection close.

(application performs operations, close)

9. Connection close, Application Server

Resource Transaction ,

(delistResource) Resource Transaction

. (end)

10. Application Sever Transaction commit,

Transaction Manager XAResource Interface

, Resource prepare commit

Transaction . (prepare,commit)

6. Java Transaction Programming

Java Transaction Programming

EJB Application Server

Transaction , Bean Management

Transaction Model EJB, Servlet/JSP

.

Java JDBC

XA Interface , JTA

. JDBC XA

Interface , Transaction DBMS

Transaction Manager, Application ,

JTA Application Server Transaction

Manager Transaction .

1) JDBC XA API Based Transaction Programming

JDBC XA API ,

DBMS Transaction , Application

Transaction .

JDBC 2.0 Global Transaction

Interface, javax.sql.XAConnection, javax.sql.

XADataSource Interface . , Java XA

Interface , XA Protocol ,

.

Oracle JDBC XA Driver , 2PC

.

import java.sql.*;

import javax.sql.*;

import java.util.*;

import oracle.jdbc.driver.*;

import oracle.jdbc.pool.*;

import oracle.jdbc.xa.OracleXid;

import oracle.jdbc.xa.OracleXAException;

import oracle.jdbc.xa.client.*;

import javax.transaction.xa.*;

import java.io.*;

class OracleXARun{

// DB Connection Info

1

16 www.bea.co.kr

Bea Enterprise Solution Technical News

final static String DB_FROM_ADDR = 127.0.0.1;

final static int DB_FROM_PORT = 1521;

final static String DB_FROM_SID = ORCL;

final static String DB_FROM_USER = scott;

final static String DB_FROM_PASSWORD= tiger;

// DB Connection Info

final static String DB_TO_ADDR = 127.0.0.1;

final static int DB_TO_PORT = 1521;

final static String DB_TO_SID = ORCL;

final static String DB_TO_USER = scott;

final static String DB_TO_PASSWORD = tiger;

// main

public static void main(String args[]){

OracleXARun oxa = new OracleXARun();

try{

oxa.XARun();

}catch(Exception e){

e.printStackTrace();

}

}

void XARun()

throws XAException,SQLException

{

// step 1. open connection

// step 1-1. create XA Data source (ResourceFactory)

XADataSource xds1 =

getXADataSource(DB_FROM_ADDR,DB_FROM_PORT

,DB_FROM_SID,DB_FROM_USER,DB_FROM_PASSWORD);

XADataSource xds2 =

getXADataSource(DB_TO_ADDR,DB_TO_PORT

,DB_TO_SID,DB_TO_USER,DB_TO_PASSWORD);

// step 1-2. make XA connection (Transactional

Resource)

XAConnection xaconn1 = xds1.getXAConnection();

XAConnection xaconn2 = xds2.getXAConnection();

// step 1-3. make connection (DB Connecction)

Connection conn1 = xaconn1.getConnection();

Connection conn2 = xaconn2.getConnection();

// step 2. get XA Resource (XAResource)

XAResource xar1 = xaconn1.getXAResource();

XAResource xar2 = xaconn2.getXAResource();

// step 3. generate XID (Transaction ID)

// Global Transaction ID , Branch

Transaction ID

// Transaction ID .

Xid xid1 = createXid(1);

Xid xid2 = createXid(2);

// step 4. xa start (send XA_START message to

XAResource)

xar1.start(xid1,XAResource.TMNOFLAGS);

xar2.start(xid2,XAResource.TMNOFLAGS);

// step 5. execute query(execute Transaction)

// FROM DB ACCOUNT 1000, TODB

ACCOUNTNO 1000 BALANCE 1000

// insert.

String sql ;

Statement stmt1 = conn1.createStatement();

sql = update accountfrom set balance=balance-1000

where accountno=1000;

stmt1.executeUpdate(sql);

sql = insert into accountto values(1000,1000);

Statement stmt2 = conn2.createStatement();

stmt2.executeUpdate(sql);

// step 6. xa end (Transaction .)

xar1.end(xid1,XAResource.TMSUCCESS);

xar2.end(xid2,XAResource.TMSUCCESS);

// step 7. xa prepare (xa prepare .)

int prep1 = xar1.prepare(xid1);

int prep2 = xar2.prepare(xid2);

// step 8. xa commit

// step 8-1. check prepare stat

// prepare commit .

// XA_RDONLY update select Read Only

Transaction

// ,

boolean docommit=false;

1

17www.bea.co.kr

if( (prep1 == XAResource.XA_OK || prep1 ==

XAResource.XA_RDONLY)

&& (prep2 == XAResource.XA_OK || prep2 ==

XAResource.XA_RDONLY) )

{

docommit = true;

}

if(docommit){

// XA_RDONLY commit

commit .

if(prep1 == XAResource.XA_OK)

xar1.commit(xid1,false);

if(prep2 == XAResource.XA_OK)

xar2.commit(xid2,false);

}else{

// roll back

if(prep1 != XAResource.XA_RDONLY)

xar1.rollback(xid1);

if(prep2 != XAResource.XA_RDONLY)

xar2.rollback(xid2);

}

// step 9. close connection

conn1.close();

conn2.close();

xaconn1.close();

xaconn2.close();

conn1 = null;

conn2 = null;

xaconn1 = null;

xaconn2 = null;

}// XARun

Xid createXid(int bids) throws XAException{

byte[] gid = new byte[1]; gid[0] = (byte)9;

byte[] bid = new byte[1]; bid[0] = (byte)bids;

byte[] gtrid = new byte[64];

byte[] bqual = new byte[64];

System.arraycopy(gid,0,gtrid,0,1);

System.arraycopy(bid,0,bqual,0,1);

Xid xid = new OracleXid(0x1234,gtrid,bqual);

return xid;

}// createXid

XADataSource getXADataSource(String dbAddr,int

port,String sid

,String userId,String password)

throws SQLException,XAException

{

OracleDataSource oxds = new OracleXADataSource();

String url = jdbc:oracle:thin:@127.0.0.1:1521:ORCL;

oxds.setURL(url);

oxds.setUser(userId);

oxds.setPassword(password);

return (XADataSource)oxds;

}// getXADataSource

}// class OracleXARun

< Oracle JDBC XA Driver 2PC >

.

1. (

RM) . DB accountFrom

, DB accountTo

.

// DB

CREATE TABLE ACCOUNTFROM(

ACCOUNTNO NUMBER,

BALANCE NUMBER,

PRIMARY KEY(ACCOUNTNO)

);

INSERT INTO ACCOUNTFROM VALUES(1000,10000);

// DB

CREATE TABLE ACCOUNTTO(

ACCOUNTNO NUMBER,

BALANCE NUMBER,

PRIMARY KEY(ACCOUNTNO)

);

< Oracle JDBC XA Driver >

1

18 www.bea.co.kr

Bea Enterprise Solution Technical News

2. final static, DB DB

.

final static String DB_XXXX_ADDR = 127.0.0.1; //

Oracle DB IP

final static int DB_XXXX_PORT = 1521; // Oracle DB

Port

final static String DB_XXXX_SID = ORCL; // Oracle

DB SID

final static String DB_XXXX_USER = scott; // Oracle

DB User ID

final static String DB_XXXX_PASSWORD= tiger; //

Oracle DB User Password

3. .

sqlplus accountfrom accountto

select , accountfrom accountno 1000

row balance 1000 , accountto

accountno1000, balance 1000 row

.

, accountto accountno

1000 row ,

, rollback .

, JDBC XA Interface 2PC

, JAVA Transaction

. , ,

, .

2) JTA Based Transaction Programming

JTA Interface Transaction

. EJB

Web Application Server(WAS) Transaction

Manager Transaction , JTA

.

Transaction Manager

, XA

, JTA Transaction

.

JTA

1. User Transaction (tx) .

2. User Transaction tx , User

Transaction . tx.begin();

3. Resource (DBMS, JMS) ,

.

Resource

. Resource Adapter XA .

Oracle , JDBC Driver

oracle.jdbc.driver.OracleDriver ,

oracle.jdbc.xa.client.OracleXADataSoruce

.

Connection (java.sql.conn)

DriverManager.getConnection

, WAS Resource Factory

. DBMS DataSource

Connection .

4. tx.rollback();

roll back.

5. tx.commit();

commit.

.

DBMS

ACCOUNTFROM ACCOUNTNO 1000

BALANCE 1000 ,

ACCOUNTTO ACCOUNTNO 1000,

BALANCE 1000 ROW INSERT .

DBMS ACCOUNTFROM,

ACCOUNTTO .

WebLogic

1. JDBC Connection Pool .

, CONSOLE .

(http://localhost:7001/console)

, Services JDBC

ConnectionPools , Configure a new JDBC

Connection Pool .

1

19www.bea.co.kr

ConfigureGeneral Tab

Name : OracleXAPool

URL : jdbc:oracle:thin:@127.0.0.1:1521:ORCL (

)

Driver Classname:

oracle.jdbc.xa.client.OracleXADataSource (

JDBC !!)

Properties :

user=scott

password=tiger

, Targets Tab Targeting .

2. TXDataSource .

, Services JDBC TX Data

Sources , Configure a new JDBC TX Data

Source .

DataSource ,

global transaction , TX DataSource

.

Configuration .

Name : OracleTXDS

JNDI Name : OracleTXDS

PoolName : OracleXAPool ( )

TX Data Source Target Tab

.

Bea Enterprise Solution Technical News

conn2.setAutoCommit(false);

System.out.println(Connection from :+conn1);

System.out.println(Connection to :+conn2);

// step 4-3 execute query

Statement stmt1 = conn1.createStatement();

String sql = update accountfrom set

balance=balance-1000 where accountno=1000;

stmt1.executeUpdate(sql);

System.out.println(Statement 1 passed);

Statement stmt2 = conn2.createStatement();

sql = insert into accountto values(1000,1000);

stmt2.executeUpdate(sql);

System.out.println(Statement 2 passed);

// step 4-4. close connection

stmt1.close();

conn1.close();

stmt2.close();

conn2.close();

System.out.println(connection closed);

System.out.println(tx :+tx);

tx.commit();

System.out.println(Transaction Commited);

}catch(Exception e){

System.out.println(Transaction rolled back due to :

+e);

tx.rollback();

}// try-catch

System.out.println(End Transaction);

ctx.close();

}// JTARun

%>

. (WINDOWS

DOS .)

Context Created :[email protected]

Start Transaction

:ClientTM[myserver+10.136.0.133:7001+mydomain+]

Datasource from

:[email protected]

Datasource to

:[email protected]

Connection from

:[email protected]

Connection to

:[email protected]

Statement 1 passed

Statement 2 passed

connection closed

tx :ClientTM[myserver+10.136.0.133:7001+mydomain+]

Transaction Commited

End Transaction

< >

7. EJB Transaction Model

, Java

. J2EE

EJB

.

1) Declarative transaction demarcation ( )

EJB

EJB EJB Container

. EJB

,

Declarative transaction , EJB Deployment

Descriptor

. , Declarative Transaction

, .

1

21www.bea.co.kr

a) Required:

Required

. CALL ,

Propagation ,

,

,

.

Required

, (update,

delete) .

b) Required New:

Required New

. ,

(

) .

, ,

,

,

,

.

, Required New

.

.

TX_A_BEGIN

DoSomething1

RequiredNewMethod(); // Required New - TX_B

DoSomething2

TX_A_END

TX_A RequiredNewMethod()

Requried New ,

DoSomething1 , TX_A SUSPEND ,

RequiredNewMethod()

TX_B , commit

. TX_A , RESUME ,

DoSomething2 , A .

TX_B TX_A , TX_B

rollback, TX_A rollback (failure

localized).

, DoSomething2 TX_A rollback,

TX_B rollback . log

.

.

,

.

c) Supports

Support

. Support

,

.

d) NotSupported:

NotSupported

.

,

NotSupported ,

suspend,

resume

.

e) Mandatory:

Mandatory SCOPE

. Mandatory

,

.

Mandatory

TransactionRequiredException

TranscationRequredLocalException

.

1

22 www.bea.co.kr

Bea Enterprise Solution Technical News

f) Never:

Never

,

. Never

.

client managed transaction

,

.

Declarative Transaction

.

( Clients Transation

Transaction . NO_TRAN

. EJB Methods Transaction

Clients Transaction , EJB

Method .

TRAN_A Client ,

NEW_TRAN Client

.)

2) Transaction

, Declarative Transaction Model

? ,

,

o DATA READ - Supports

o DATA UPDATE - Required

o Resource

- NotSupported

MDB (Message Driven Bean) Required

Not Supported .

3) EJB Deployment Descriptor Transaction

EJB

EJB Deployment Descriptor ejb-jar.xml EJB

, .

ejb-jar.xml .

EJBNAME

EJBMETHOD_NAME

.

4) Bean Managed Transaction

J2EE Declarative

Transaction Model . EJB

EJB Container ,

Transaction , BMT (Bean

Managed Transaction) .

Bean Managed Transaction, email, file

resource

, ,

stateful session bean, ,

, Transaction ,

.

1

23www.bea.co.kr

Transaction

Attribute

Clients

Transaction

EJB Methods

TransactionComment

RequiredNO_TRAN NEW TRAN

TRAN A TRAN A

Required NewNO_TRAN NEW TRAN

TRAN A NEW TRAN

SupportNO_TRAN NO_TRAN

TRAN A TRAN_A

Not SupportedNO_TRAN NO_TRAN

TRAN A NO_TRAN

MandatoryNO_TRAN Error

TRAN A TRAN A

NeverNO_TRAN NO_TRAN

TRAN A Error

Bean Managed Transaction

EJB Context , UserTransaction Context

Transaction .

.

, javax.transaction.UserTransaction EJB Context

.

UserTransaction begin

.

,

, commit rollback .

Bean Managed

Transaction .

// Bean Managed Transaction Session Bean

import javax.transaction.*;

:

public class BeanManagedTransaction implements

SessionBean{

SessionContext ctx = null;

public void setSessionContext(SessionContext ctx){

this.ctx = ctx;

}// setSessionContext

public void startTransaction(){

UserTransaction utx = ctx.getTransaction();

utx.begin(); // .

}

public void doSomethingA() throws Exception{

:

try{

// do something about db transactions...

}catch(Exception e){

:

UserTransaction utx = ctx.getTransaction();

utx.rollback();

throw new SomeException();

}finally{

conn.close();

}// try-catch

}// doSomethingA

public void doSomethingB() throws Exception{

// simliar to doSomethingA

// do something about db transactions..

}// doSomethingB

public void endTransaction(){

UserTransaction utx = ctx.getTransaction();

try{

:

utx.commit(); // , commit.

}catch(Exception e){

utx.rollback();

}

}

}// class BeanManagedTransaction

// in client code

BeanMangedTransaction bmt = .....;

:

try{

bmt.startTransaction();

bmt.doSomethingA();

bmt.doSomethingB();

bmt.endTransaction();

}catch(Exception e){

// transaction has failed

}

Session Bean, ,

DB ,

. ( Session Bean ,

EJB Client ,)

Client BeanManagedTransaction SessionBean

bmt ,

startTransaction User Transaction ,

doSomethingA doSomethingB, DB .

, UserTransactionContext

, rollback , Exception Throw,

1

24 www.bea.co.kr

Bea Enterprise Solution Technical News

Transaction stop . , commit

, . Method

, 4 Method .

Session Beans Stateful

Session Bean . Stateless

,

.

Bean managed transactions ejb-jar.xml

, Bean Managed

Transaction Bean transaction-

type Bean .

:

BeanManagedTransaction

BeanManagedTransaction

:

Stateful

Bean

:

Bean Managed Transaction

, ,

Method Stateful Session

Bean . Stateless Session Bean

User Transaction ,

.

Bean Managed Transaction Bean

Session Bean Message Driven

Bean . Entity Bean .

5) Transaction in Entity Beans

, ,

Entity Bean Transaction

.

Entity Beans ejbLoad, ejbStore

Declarative Transaction Model , Support

. Entity Bean Client

Transaction EJB .

Client Transaction A ,

Entity Bean ejbLoad ejbStore

Transaction A . Client

Transaction , Transaction

.

, Bean

Transaction ,

Entity Bean ejbStore Data write

, Entity Bean Data Writing

, Client Data

write .

.

( .)

Entity Bean Transaction

Required . Required

client transaction

transaction .

Entity Bean Activation, Passivation

, ( ,

EJB .) WAS

Caching . Entity Bean

Passivation , Entity Bean Client

Transaction , EJB

client DB writing

commit .

, client CA

. ClientCA EntityBean EA

, doSomething

, EntityBean EA DB

.

, EntityBeanEA update , Entity Bean EA

Passivation , EJB DB

update , Entity Bean EA

, DB commit

.

1

25www.bea.co.kr

, client CA doSomething

, doSomething call

? Entity Bean EA commit

, .

client CA call

, DB , passivation

DB .

EJB Entity Bean Container

Management Persistance(CMP)

EJB Entity Bean client

transaction .

6) EJB Transaction API

EJB Transaction Method

, ,

.

a) setRollbackOnly()/getRollbackOnly()

setRollbackOnly() ,

Transaction commit .

MA, MB, MC , MB

setRollbackOnly ,

rollback , MC ,

Transaction , rollback .

setRollbackOnly , rollback

Logic , Transaction

rollback mark .

Container Management Transaction

, Required, RequiresNew,

Mandatory .

, rollback ,

getRollbackOnly() .

b) afterBegin,afterCompletion,beforeCompletion

EJB Session Bean Container Managed

Transaction , javax.ejb.SessionSynchronization

interface , call back event

. , /Commit

interface implement .

public interface javax.ejb.SessionSynchronizaton{

public void afterBegin() throws

EJBException,RemoteException;

public void afterCompletion(boolean commited) throws

EJBException,RemoteException;

public void beforeCompletion() throws

EJBException,RemoteException;

}// SessionSynchronization

.

afterBegin() ,

, . beforeCompletion

commit .

afterCompletion commit/rollback

, commit commited value true,

false . (afterCompletion

Context

.)

, Data sync, caching, format

.

7) Programming Two-Phase Commit using EJB

EJB Oracle

DB Two Phase commit .

EJB .

A B

Entity Bean Session Bean .

1

26 www.bea.co.kr

Bea Enterprise Solution Technical News

a) ORACLE XA

step 1. sql plus .

% sqlplus sys/[email protected]

ALIAS NAME

step 2. XA .

% grant select on DBA_PENDING_TRANSACTIONS to

public

b) ORACLE

2PC , ORACLE DB

.

DB A :

SQL> create table TABLE_A(

2 ID NUMBER UNIQUE,

3 ACCOUNT NUMBER,

4 PRIMARY KEY(ID)

5 );

6 insert into TABLE_A VALUES(1,1000000);

DB B:

SQL> create table TABLE_B(

2 ID NUMBER UNIQUE,

3 ACCOUNT NUMBER,

4 PRIMARY KEY(ID)

5 );

c) EJB

EJB , AccountManager,

AccountBankA, AccountBankB 3 EJB .

AccountManager EJB Session Bean transfer

. transfer AccountBankA

EJB TABLE A balance

srcAccount , AccountBankB EJB

, DB TABLE_B update .

AccountBankA .

AccountBankA EntityBean.

set/get . AccountBankB

AccountBankA AccountBankB

.

// AccountBankA.javapackage com.javastudy.twopc;

import java.rmi.RemoteException;import javax.ejb.EJBObject;

public interface AccountBankA extends EJBObject {public Long getAccountId() throws RemoteException;public long getBalance() throws RemoteException;public void setBalance(long balance) throws RemoteException;

}

// AccountBankA_Home.javapackage com.javastudy.twopc;

import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.EJBHome;import javax.ejb.FinderException;

public interface AccountBankA_Home extends EJBHome{public AccountBankA create(Long accountID,long balance)

throws RemoteException,CreateException;

public AccountBankA findByPrimaryKey(Long accountID)throws RemoteException,FinderException;

}

1

27www.bea.co.kr

// AccountBankA_EJB.javapackage com.javastudy.twopc;

import javax.ejb.CreateException;import javax.ejb.EntityBean;import javax.ejb.EntityContext;

public abstract class AccountBankA_EJB implements EntityBean {public abstract Long getAccountId();public abstract void setAccountId(Long accountId);

public abstract long getBalance();public abstract void setBalance(long balance);

public Long ejbCreate(Long accountId,long balance)throws CreateException {

setAccountId(accountId);setBalance(balance);

return null;}// ejbCreate

public void ejbPostCreate(Long accountId,long balance)throws CreateException{}

public void ejbActivate() {}public void ejbLoad() {}public void ejbPassivate() {}public void ejbRemove(){}public void ejbStore(){}public void setEntityContext(EntityContext ctx){}public void unsetEntityContext(){}

}

AccountBankA AccountBankB

AccountManager Session Bean.

//AccountManager.javapackage com.javastudy.twopc;

import java.rmi.RemoteException;import javax.ejb.EJBObject;

public interface AccountManager extends EJBObject{public String transfer(long srcAccount,long balance,long

desAccount)throws RemoteException;

}

//AccountManager_EJB.javapackage com.javastudy.twopc;

import javax.ejb.CreateException;import javax.ejb.SessionBean;

import javax.ejb.SessionContext;import javax.naming.InitialContext;import javax.naming.Context;import javax.naming.NamingException;import javax.rmi.PortableRemoteObject;

public class AccountManager_EJB implements SessionBean{

public String transfer(long srcAccount,long amount,longdesAccount){

AccountBankA accountA = null;AccountBankB accountB = null;String result_msg = null;// AccountA AccountB Entity Bean .accountA = getAccountBankA(srcAccount);if(accountA == null) return cannot cat account A:

+srcAccount;

accountB = getAccountBankB(desAccount);if(accountB == null) return cannot cat account B:

+desAccount;

/* start transaction */try{// AccountA AccountB Entity Bean BALANCE

// A balnce B .

long balanceA = accountA.getBalance();long balanceB = accountB.getBalance();

// .System.out.println(current balance A :+balanceA);System.out.println(current balance B :+balanceB);System.out.println(amount:+amount);

accountA.setBalance(balanceA-amount);accountB.setBalance(balanceB+amount);}catch(Exception e){

System.out.println(Error occur duringAccountManager_EJB.transfer:+e.toString());

return e.toString();}/* end transaction */

return null;}// transfer

private AccountBankA getAccountBankA(long accountID){AccountBankA accountbank = null;

try{Context ctx = getContext();Object obj =

ctx.lookup(com.bea.twopc.AccountBankA_Home);

System.out.println(AccountBank_A lookup is :+obj);

AccountBankA_Home home =

1

28 www.bea.co.kr

Bea Enterprise Solution Technical News

(AccountBankA_Home)PortableRemoteObject.narrow(obj,AccountBankA_Home.class);

accountbank = home.findByPrimaryKey(newLong(accountID));

}catch(Exception e){System.out.println(error during

AccountManager_EJB:getAccountBankA:+e.toString());

return null;}

return accountbank;}// getAccountBankA

AccountBankB getAccountBankB(long accountID){AccountBankB accountbank = null;

try{Context ctx = getContext();Object obj =

ctx.lookup(com.bea.twopc.AccountBankB_Home);

System.out.println(AccountBank_B lookup is :+obj);

AccountBankB_Home home =

(AccountBankB_Home)PortableRemoteObject.narrow(obj,

AccountBankB_Home.class);

accountbank = home.findByPrimaryKey(newLong(accountID));

}catch(Exception e){System.out.println(error during

AccountManager_EJB:getAccountBankB:+e.toString());

return null;}// try-catch

return accountbank;}// getAccountBankB

private Context getContext()throws NamingException

{Context ctx = new InitialContext();return ctx;

}// getContext

// callback methodspublic void ejbRemove(){}public void ejbActivate(){}public void ejbPassivate(){}public void setSessionContext(SessionContext sc){}public void ejbCreate() throws CreateException {}

}// AccountManager_EJB

//AccountManagerHome.javapackage com.bea.twopc;

import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.EJBHome;

public interface AccountManagerHome extends EJBHome{AccountManager create() throws CreateException,RemoteException;

}

9 .AccountBankA.java

AccountBankA_EJB.java

AccountBankA_Home.java

AccountBankB.java

AccountBankB_EJB.java

AccountBankB_Home.java

AccountManager.java

AccountManagerHome.java

AccountManager_EJB.java

9 .

% javac -d . *.java

, ~/com/javastudy/twopc

9 class .

d) EJB

EJB Deployment Descriptor

.

AccountManager_EJBcom.bea.twopc.AccountManagerHomecom.bea.twopc.AccountManagercom.bea.twopc.AccountManager_EJBStatelessContainer

1

29www.bea.co.kr

AccountBankA_EJBcom.bea.twopc.AccountBankA_Homecom.bea.twopc.AccountBankAcom.bea.twopc.AccountBankA_EJBContainerjava.lang.LongFalse

accountId

balance

accountId

AccountBankB_EJBcom.bea.twopc.AccountBankB_Homecom.bea.twopc.AccountBankBcom.bea.twopc.AccountBankB_EJBContainerjava.lang.LongFalse

accountId

balance

accountId

AccountBankA_EJB*

Required

AccountBankB_EJB*

Required

AccountManager_EJB*

Required

ejb-jar.xml . AccountManager EJB

Stateless Session Bean,

Required . (, AccountManager

AccountBankA AccountBankB EJB

ejbStore ejbLoad AccountManager

.)

Weblogic WAS EJB deploy

descriptor . Weblogic

weblogic-ejb-jar.xml weblogic-cmp-rdbms-jar.xml

, .

.

descriptor

http://e-docs.bea.com/wls/docs61/ejb/index.html

.

WebLogic EJB Deployment descriptor

.

EJB ( EJB ~/com/javastudy/

twopc ~/ .) java

weblogic.ant.taskdefs.ejb20.DDInit. (WebLogic 6.1

, WebLogic

.) EJB Deploy 3

descriptor . DataSource

,

, .

deployment descriptor META-INF

.

~/com/javastudy/twopc 9 EJB,

~/META-INF/ 3 Deployment Descriptor

.

~/ jar

twopc.jar .

% jar -cvf twopc.jar ~/*

e)

EJB , EJB Deploy EJB

Container .

Entity Bean DataSource .

1

30 www.bea.co.kr

Bea Enterprise Solution Technical News

WebLogic Console , Services > JDBC >

Connection Pools Create New JDBC Connection

.

JDBC Connection Pool

, JDBC .

Driver Class XA , JDBC Driver

. .

JDBC Connection Pool Target Tab ,

Server .

Connection Pool .

Connection Pool DataSource

.

ServicesJDBCTX DataSource Configure

a new JDBC TxDataSource .

JDBC TXDataSource

.

OracleXADS_B .

f) EJB DEPLOY

EJB Deploy Oracle RDBMS EJB

Container WebLogic . EJB

Deploy .

Deployments > EJB Install a

new EJB . , []

, twopc.jar deploy

. Deploy , target , server

targetting .

g) CLIENT

EJB Deploy , TEST

1

31www.bea.co.kr

NAME

JDBC Connection Pool,

OracleXAConnection_A

OracleXAConnection_B .

URL jdbc:oracle:thin:@IP Address:: SID

Driver

ClassName

oracle.jdbc.xa.client.OracleXADataSource

Propertiesuser=

password=

NAME OracleXADS_A

JNDI Name OracleXADS_A

PoolName Connection Pool .

OracleXAConnection_A

. TEST CLIENT .

// TwoPC.java

import com.bea.twopc.*;

import javax.naming.*;

import javax.ejb.*;

import javax.rmi.*;

import java.util.*;

public class TwoPC{

public static void main(String args[]){

try{

// step 1. get AccountManager

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY,

weblogic.jndi.WLInitialContextFactory);

// .

env.put(Context.PROVIDER_URL,t3:// IP:

);

env.put(Context.SECURITY_PRINCIPAL,system);

env.put(Context.SECURITY_CREDENTIALS,weblogic);

Context ctx = new InitialContext(env);

System.out.println(ctx :+ctx);

Object obj =

ctx.lookup(com.bea.twopc.AccountManagerHome);

System.out.println

(com.bea.twopc.AccountManagerHome Jndi :+obj);

AccountManagerHome home =

(AccountManagerHome)

PortableRemoteObject.narrow

(obj,AccountManagerHome.class);

AccountManager manager = home.create();

// step 2. run transfer method

String result =

manager.transfer((long)1,(long)10,(long)100);

// step 3. display result

System.out.println(result is :+result);

}catch(Exception e){

e.printStackTrace();

}

}// main

}

WebLogic Class Path ,

.

% javac -d. TwoPC.java

h) CLIENT

Client ,

% java TwoPC

, DB TABLE_A VALUE

100 , TABLE_B . TABLE_B

, , ,

TABLE_A 100 ROLL BACK

..

, EJB

.

, , , EJB

.

EJB 3

Transaction Component ,

, . EJB

, ,

. EJB Container, EJB

,

..

EJB 6

.

Container , Logic

, ,

, Bean Managed Transaction

.

1

32 www.bea.co.kr