• An a II·i nc'us lvc boo Ie: to teach you eve rvth ins .abol.l~ EJIll.

O

• Ea~)o' ~ I~H eel lve r iI nd Rcllabtc

• Quick and E.J5.y le'ilfni~,;n Si mp le SI cps

• Mosl pre lcrrcd choi co worldwide (or le.M;mi,ng EIB 3.0

E_

3.

CtnI'OI r>'l:r1,lD" ng

This 1>"'1" d;"ploys a tat of Java EE "PP'u\i<nl _ oil; 'dom~n. h1.tal kld appl'cations .o:r 'rra:l!iaS CO!1 00 S .... IT., selei:trg !too appllcati;ln n'if".. _ u.iog """' mntr

---

tCQ)p)'rig/U b)' Oreamteeh hess. 19~A. ADWi Ro.ad.~DI~aftj. New Delhi~t J,0002

Thi:s. book may nnt be duplicn.!M til 4fi1' "'By YIo'ilbolLt (he ~~ wnlkn consent of the pLlbli!berj clap!: in me I forru of brief ,cxtcrp11i or qoot.a.tiOOJl. for' 'he putpl'lSC5.of revtew. The .information eemateed he.reiD j_, fot i.he ' p:rsorul'1J~ of ll'Ie Iftdcr and may Dot be ift1:orpom.cd in flO)' com.mert'ial prugrams, <Mer books., dilll:abues. or J :a;ny kind of sonwi1l'e with:mtt writtel'l C01"lsaU or Ihe pubUt:her. Muing ~es of this book Of any porIiOIl tOt iiI(1)' pwpose c .... ar lJII)Il,ygtP" I)Wl1 iiO!I viol:lliotll;Jlfl;:l;IfIynSbt bW5.

LjrnitJ of ,Liabtlity/di$Ctatmer of Wmanty; The atJthor end ~tW1ff have 'U~ their bc:it cffort~ in ~.s !hili: book_ The author rno.Ic.- no rcprescntsucn or werranties with ~I to the !KX:lJ1lICf DJ" cotnpletenesa of ihe O)jItcrtls of this book, and gpecifiailly disc!llim ilD~ implied ","llrrSL'u.ies of Il'lC1't"hantability or fimes! of lit)' pra:1i~uI.u purpose. There at(! DO wmti'l.Dti~ wh~ (!:('l,(f.Jd beyo:tld the dcscd~jOM 'contai.nr::d. in thi.! paragn;.b. No warran~ mity be C'I'e3Ilcd or ex'cOOed by sales repreeeuadves or wriuen Sillies materiillls, The IC'CW'aC)I and oompJ(ter!o~s I;)f ~ iofOrrn;llllo,!']: pl'~n,'ided herein iUid dte- "'~_lli~ Sl2Iled hm=i~ 3U= n(:( ~I.:ed or wamr;p!~ to PfOodIX'e an)' patlicillus reiiult!~ ;and me aci'l,'jcc and ~gies contained herein rnJly nor be :o.Illitable for every iJuiimDat" Neither Dream.le:co ~ nor !!IJutnOf sball be li;llble for ·any b;~ of p~flt o:r :my O!ha- co:rnmcrciat d:unagn. inc'huling but nor limited to 5fl"CilIl. :im:idcmal, censcqueetiel, Dr other damages.

Tradl:rnarb: AU brDoCd rwnes and product ,ctuDl:$ used in lbis book ,It I'<!: tr.\dermrb,. regtsered n~ or ~, names of theft' respecave holders. xm:lmtcch Pres:!. 1! .cD! lW()i:intod with IlnYprodlJCt or 'Vendor rnauioned ln thle book.

ISBN: IO-ijl·712H!l'J

) l - 9'~·81· 77:!1· 7\!'·6

Edition: 2008

Printed al ; P,imM.n (India). Delhl« 110092

U rheberrcc htlich gesc h utztes M ateri a

CONTENTS

Chapter 1 • Introducing fJ8 1

,

......... ", .. " _ -

lava '" eli .nl _....... _., , 4

lava EE 5 Conra i """ "........................... . .. ,_ 4

Introduction to EIB _ .. _._ 5

Mas~go- Drj,vcn sesn ,_._ .

" ......... ,6

Previous Versions Qr rJA

B

1Q

__ ._" " 10

]1

Dependency I njedion . . __ n __ n. __ n __ n. __ .. __ .. __ .. •

.12

POlO Model .,,_ ....... _"'

lJ

El i mlnatlon of Home tnt~rla.c:c and H orne Obi ects .. _., .. ,m ,_ •••• , ... , m .....

.13

Elilliln:1lioli of Ccrnpcneru Interface , ...

" .,14

I nlelceptors "' .. "' , .

..",, __ 14

]4

Summary " "" _ 15

I "ired! letion

18

Concept of Session 6~ n .. _._ . __ ... _., ._.,

...................................................................... 18

S tal eless Scssio n Be;) n

19

Life cyt,1 e of a Slate-less Sessl on Bean . . . . __ n m.

" 20

E1emcn t~ of Stjlt ... ,,.s,;; Sr .. sion R [Iojl n

,22

Deployment .... _" "_ .. "_., .. _, _"_.

".28

Sta'e(J J I _Sess jon _e ean

35

Ufe Cy<:le of Sialelul S",,;oo B~ n " " .. " " " .. " ..

. J6

Developing" Slal.ciul5es,ion Bc." ..... " .. " ...... " .. " ... " .. " .......... " ..

Ct-.x..;ng lIelWec" 51.leI." 0' SlOwf u I S""ion am n , __ ' __ . __ n .. n.'. . 4 J

Summa'y .44

v

U rheberrec htl lch gcsc h utztes Materia

M~!iis.aHinB, Conl:~pt " _ " 46

IMS

".,,_ .. , .. ,.,., .. , .,',.,., ,',.,.,., " .. , , .. , , .. , .. , , , ,.,., ,.,., .. 47

\'Yb:,t i$ MPH?

')0

WIlY to use MDm " .. " ..

. :50

S+Wcfll[f" 01 an MDB

51

life cyde of Mes"S" D,j_ Be,n " , .. , ... , , " .. " .. " .. , , .... , .. " .. , ... , " , , ... " , , ... 52

Writing uri .-.;Do ... , , " .. , ....... " , .. "., ,.,.,.,., ,.,.,.,.,., ... ,.,., , , .. , ,., .. 54

s..u rnplc Aprl ication __ _,_.00,_ .. _,_00. nn nn m nm nn nn""'_ n nnn n no m moo m nn nnn m" nn nm nn 55

DoplQying 'ho [I ~ ""'" ". ,,"" .. ",' __ ". " __ ,, ,,, ". " .. "", 6"

Running the APpllC3tion ...

, , , ,,75

Summary' ... _ .. _ n _. _. n _ •• _ n _. _." _._. __ ._.

"" _",,,, .. 77

Chal!ler 4 • Transactions • . . 79

!nlrndL If! i on

80

T ransa ction- \I\,o'here !hey are tou n d ~

_'_''''_,''''_'''_'_''_'''_,'' __ .. "' __ ",'_""'.,' __ , ",,60

Online Book Store

BJ

Mooi ca I Sy,wm n

... 81

Why do we Need Transactions]

""""""""". ", .. 81

Trj] m.iJ ctl on Proncrt i es _._ ••.•• _ .•• _

_,_,,"'_,_,_,_""'_"',',""""""",'_,_"'_,_""",,82

Atomic itv ...

.. .. 62

Cceststcn C'I,'

_ , .. &l

".M

84

fH

Cb[1jned Irj]DSi1ctjno5,

85

SaRa Tra reactions ........

"""' __ " __ "'_",_",86

Distribl urd It;! n-sa oj OOS.

87

The Two_ P tt 1 Sf" (omm H Protocol

oa

lran,.clion SupPOrt in SIf! 3.0 .. _ , , , , , 88

lava T ranscctlcn API flTAl .. _."._ .. _ ... " n'.n"

68

Conl.a i nerr!'v1.looged Ira nsactlons _ _ .. "._" n."" _ ••• n." __ •

__ """""' __ "_" __ "'_"""""_",_,,89

8e.ln ·MiUlaged Tf.] nsact Io ns ......

__ 93

Sum!nary n n _

"" __ " __ "" "" __ ."."_ 9_~

I nuodl Ie! tnn 9'1

Object-Relational Mapping !ORM) n n , , ,98

tntrcducuon !o f;ntitv .

________ ,, 99

vi

U rheberrec htl ic~ ge5c h utztes M ateri"

Conlcnts

Spec;(y I nR the to ENTITY , ..

Spccilyi n~ Ihe ~Col" m ns, .t 07

Sp~[fying ~ Enumerated ._ __ __ .. n. __ n __ n n_._ n., n., n_ •• __ ., _. , .•••••• _., , , .. , , .. ,' n , 108

Spedlying the G>Lob " ... , .. " ... ,._. ..m_m_m. 108

Specifying Ihe OTemporal,m" .. " m,.m "m , ' 'm ' ' , , _ 109

Enlity 'nd Session bean, .. ", .. , .. ", .. ,m" .. ,m, .. " " .. , .. " .. " .. " ".,,'" _ .. "" 109

When To Usc Enlity nean " 'm ' " " .. " .. " .. " .. ,m.

.. ..... " .. " ...... " ... 110

l'ntityd."_ _ .. ,,_ , 'm' ' m' •••

.. " " .. "Ill

Enl i Iy ma nager API, _, .. , ,

....... 111

lif., Cvr le of l'nlity " ..

. 112

PrOY,jder 'J' 1 5

it.)-dala-SoOurcc. non i~l-duta-50lJrce .. " .. "."m"n.m,m"n " ... m n, 1 '1.5

Mapping-fil~ nn ..... __ nnm ..... __ n_ .... m ..... m.m. nn. __ nnnnn ..... m.m.m._._._. .m t 15

Obtaining,n Entity MaMger........................................... .. , 11' 7

sess Ion Bean !"iSLng tnc Con.a i ncr I njOCI ion ,._. n._" _._, m •••• , ••

.." 117

Obtain i ng EntitvMan.ager us ins, EntilyManasC'rFactory .1_ •.• _ •.•

__ ,,_.117

Obta in i ng fntil"yMa nager by lockt ng u p us! ng J NOI

Cr!li1rtng.a ~mple Appli.:at'iorl .•. __ 00._._. ._._.00_, .00000000_ 0000_ ••• _._. _. ._,_,.,.,11.8

Compiling the lava classes ." .. "._" .. " .. " .. " " " .. ".. ..." .. 130

OOI>loylng the Samplo Applic.llon .. " .. "_ _.,,.... ..." .. In

ExeculinB Ihe Sample Applicalion "............. _,."" ,,,,,,,,, 137

Summary., ,.,., ,.,.,.,.,.,., ,.,.,.,., , , , ,., ,.,.,.,.,.,.,., 139

Introduction to !PQL .,.,.,.,.,.,.,., ,.,.,., ,.' ' n'.'.'.,.,.,.,.,.,.,.,.,., , ,.142

JPQL. statements ." .. " .. ,', .. , .. " .. , .. "m, ... " .. ,m, .. ", .. " .. " .. " •• " .. ", .. , ••• " .. " .. " •• ,, .. "m, .. ", .. , .. ,.143

The Sfl EO (;[atomrnt 1 41

Th;. 0 EI FIE s"jWm,.nt 144

I9L Funci iQ.n.5 00_ .. 00_ 0000 n_n •• 00.0000 0000.00_.00 .. 00_.00_.00_.00_.0000 00_.00_ .. 00 .. 00.00_.00 .. 00_.00 .. 00_ 0000.0000 n_n 0000. _ 14.5

StJLng functions "_ •• __ ., a_

"" .. 145

d rj tb roM;' ,.! OO·jo"s

".".147

147

149

vii

U rheberrec htl ich gesc h utztes M a\eria

£/8 J,O '" Simpl. Slrps

GROUP BY HAVING (Iau",. _n __ n n n __ oo __ oooooo __ oo oo •• __ • oo __ n_ ....... 149

OORER By (1.1"",e J 50

mND!TlONAJ FXPRF~SION 1 ;0

P"th .e):~ples.'Sions__ _nn m __ n. nn m •• __ m. __ nn •• __ .m. " :51

U, inR Lhe BETVl/cc N "I>"rOIO r .. ,, __ " "_ ,,, ._ _ ,,., 152

U~if!g (he IN operator .... __ nm. __ n ..... __ mm.m ..... __ nm. __ nm. __ n._______ ,152

U5ing.l.he LIKI:: oncrasor n_. n __ . __ .. __ nn_'. n. __ .. • __ ._ _. • ••.• _.,_._ •••• " _ •• ,.52

Using the NUn operator , .......

, .. , , .. " " ,. , .. , ISl

_ .. 153

JPQL cotlecuon memher C'x[l~jQIl

__ ..... 1,4

JPQL EXI.STS ""p"",ion<.",..".",.." .. ,,..,,,.,,,.

,.." .. " ... 154

J PQl ALL. A NY and SOME ""p"",iOO' ,. " , ,,. " .. " _ ,. " , 154

lOINS

154

Inner Join " ... rr." •• ,', •• " •• ",."r."r.",.

Loit Oul<''' Iotn., _ .

Fetch loin _ , .

Query API , , ..

" ... , .. " .. " .. " .. " .. " .. " .. " .. " .. " .. " .. " .. " ... " .. " .. " ...... 155

__ .. .. _ ...... .... _ .. , .. 155

, ....... ,. .. " •• ,,..,,. .... , •• ,,. ..... 1 S5

,., ,.,.,.,., ,.,., ,.,., , , .. , ,.,., , 15&

Dcfin i I'Ig Dvnamlc que,ies.

,,, .. 156

Odi n i ng Named queries; . . __ ... _ ... . __ ... __ . . . .. __ . .. __ . .. . . .. .. . .. __ .. . 157

Executing Queries .. _157

Cn:'.ating a Query i"n:smnce.... ,n"n, , 513.

Crear ins Nilm.x:lQuery jn~a rices.

__________ . . 15B

Crear ing dyn.lmit:;: qUery i nstaoces

.. 1,6

QLler)' Interface .. _.nn'n .• __ ".n."

,, 1,9

Parameter :selling in {]um'Y·" .. , ... "n,n., ... , ...

.. .. 160

160

Rctri evl fig a Co! locnon of cnlittcs, .. _ .. , m

................... " ....... " ...... 161

______ __ __ , " .. , 161

Controlling the flush mode n .. __ .n .. m .. __ mn .. n .. .m.m.n .. n ... n.m .. n .. n .. n .. m.n .. n .m.mn n. 161

Sf>eCifying Query hint,_ .. _" .. " ... ,. ..... ",."......... __ m.mm .. m .. oo .. oo. 162

Summary , ..... __ ., .. " .. _. __ . " .... _._ ... , .... ,_ ... _,.,. _'_n._._'_'_'_._.n_'_.

__________ 162

M. "y.\O-On" ... , ... , ... ,.,., ... ,.,.,.,.,., ... ,.,., .......... , ... ,.,.,., ... ,.,., .......... , ...... ,.,.._

... 177

M.1.r:ly-tcJ..M(ilny n' ••• ' ,._ •.••• , ~_ •••• ,._ _., ••• ,_.

,,_182

Map ping Coil ecnon- 8 ased Relat ion,h ip, ,.,., .. _,., ..

.. .... _ .. ,,_, ...... 169

E mity ["hell ta nee.", ... ,.,.,.,.,.,.,.,.,., .. "., ,.,.,.,.,.,.,.,., ",.,.,.,.,.,.,.,.,.,.,., .... ,., ..... ,.,.,., 190

Singl. reble per d.", hier.,chy ."" " .. " .. " .. " "." ".. "." .. 194

Sep.1rote table per ,"b<l.",., _.moooo •• __ .m.oooooooo.oooom.oo 'm.' •• "oo." " .. , .. " , .. " 197

Singh~ labl!? per Concret~ eriti!v d;1~5. ,n , ••• ,_ ••••• _., •••• , .. , ._ •• _, ._ ••• _. '-' __ .'.n ,_. n. nn m " 98

Summ,uy .,., ..... ,. _ .. , ... ,.,., ... , ... ,.,., ... ,. " , ... ,.,. .. ,.,.,.,., ... ,.,.,.,.,.,.,.,.,.,.,.,.,., ... ,.,.,., ... ,.199

viii

U rheberrec htl lch gesc h utztes M a\eria

C""I",,' ..

Chapter 8 • Ej B :l.IJ Til1ll!r Services . 101

EJB 3.0 Time, Service .. ,., ,.,., .

Dffferent Types of Timers ." ..

.. .... 202 20]

Timer Servjce APi

2m

_2Q4

The- Tfrner Interface , ... " .. ,', ..

The TimcdObjecllnlllriace " ..

The TimerH.1ndle toterrcce .

U,ing Time, Se"'k"' " ,_

, .. ,:W5 .. .. 207 , .. ,207

, ... ,.,., ...... , ... " .. ".,.,., ... , .... ,.,., ... , ....... 208

C"", i ng Ti met Objects

Canocllanon ..... _ .. ... __ , . . . .

E-:..;pi~·ation", •• " _ •• '"' ••• " •• " .... , ... " •• ,' •••

Strenglhs and Limitations of EJ8 Timer Services Creating') Sample Application using Timer Sen .. -lce , Pep loying theE! 0 _

RLl.nlli ng the Applkilt10n .. ,.

" " .. ,209

..." " 211

..." " 21 ,

___ .,_.2'12

. 21.1

_ __ . __ .. . .. __ .. .215

", .. " ... " .. ,215

Sum mary ,.~_. _ ... _, , .. _.~_

Chapter '} • Interceptors . . 2: 19

What are rn!erceptors~

.,_ .... ,., ...... ,.,., ... ,., .... , ... , ... 220

I nterceptor li feeye Ie ,_

... ,.,.,., .... ,., ... ,.,. ,_,.,.,.,., .. ,.,.,.220

Spec;:i lying Inlerc.eptors . _. _. _. _. _. _. n n. _. _. n _. _ .. __ . n. _. _. _. n _. n. _. _. _. _. n n. _. n n. _ n. _. _, _. _. n n n. _. _ 2 2 [)

In IOr.-.<lQlOr class ....... ,., ...... "_,.,.,., ...... ,.,.,., _,.,., ...... ,.,

_. . __ ... _222

Applying htterceptc ~ ihrough XML .. " _. , ........ " ... , ....... ~ .... , .... " ..

.. .... 223

Disa b ling I r .. en::eph~Us. •• ,." •• ,',.,', •• ,',.,', •• ,' , .• ,', •• ,' ••• , •• ,', ••

__ " .. _" ..... 224

Using AnnQ!_ll!jon~, __ . __ 224

Programming by using the nustncss Methods .. __ .. . . .. __ ... _ .... _ .... _._" , __ ".,._, .. 224

Programming b)' using tho life Cycle Call Back Molhods ".. " .. " " 225

Sp<l<i!yins. :Oel.ulllnl.orccplO' Method, .... no .. no" ....... "... no no 22f>

Life cycle Coil B.ck Method. in an lnterceptor CIa,,_,

@P"':Oestroy .... " .. ,', .. " ... " .. " ..

1m !jootCon~j;[Juct .

c:lJPllilA.CIi1./aIEL" •• " ••• ", .•• " ••• , •••

grrCPaS5 iv:a1e

_._228 ..228 .. 228

" .. " " 228

2':tq

Life Cyc.le Call back IntNcCP[o:r Methods 'i n a MDIl ._._ . __

, ... , ... , ... 229

_1)'

Exception H.ndling ..

Abcrti nB a method i nvocatl on ...

" .... 233

.... 234

. .. _ .. __ .. __ ... __ .. __ ... .. .. __ .. _ .... __ .. __ ... __ .. 234

Summary _.nnn __ n._.nn __ ._n .nnn_. __ n __ nn._._._._._.n __ n._._._,_,. _. ._ .• , ••• ,.".,.,.,., •••• ,. _ .• _ • .235

ix

U rheberrec htl lch gesc h utztes M ale,ia

EJB 3_0 ill Simple SI'1"

.&.bi!p:~ . 137

I n trod. !Clio n

__ ._ . .llII

Securirv V'orations , ,l,J,fi

Alltbeorieatign and AI'rtboriztdfpn , , , .2..19:

A'ltbcotkalion

.•••••••.•••.••.••••.•••.•••..••.••• __ , ., , .2J.')_

A.I tb!"n'iC,;)tj 0 n Srhem{>4';

______________________________ . , .. ,...ll2

AI rtborjZH Ijon

___ _ _ _ ,_, ,', .. .zsz

UserS... grou~, re.alm'§:l .lnd rtlles._.,.. , .. ", n" .. "n. " .. " ...w.

fJB Socu'itv ".,., , , , " .. " ,., ,.,.,., ,.,.,.,., ,.,.,.,.,.,.,.,.,. __ .. ,., . .:M.l

T'M'port Security with SSL .. , ... , .. " " .. ".",.".. .. ......... _ .. ...2M

Rol ... ;o._B.}~ ~uriry •. __ . __ n. __ m __ '_. __ ••• • __ •• __ ... __ •• __ •• __ • .. __ • .. • • __ ... __ ,., _. • __ •• ._~

Dedi!lfali:ve 5«:urily " __ "n"'."" •• , .. " ••• , •• ~

rf"CIgr ammatic Secur.ity ., no .. , .. , .. Pro~(.'(ti on Dom:'l.in 5(!(:ud tv .. , ..

JMSS<l<urity.-. __ . ...

, , , " .. , " , , , . .2ll

.. .. __ .2!.6.

_. __ . .2!.6.

"IAA_::"",S"I"m",p",leme:",.",n_".ta",ti"onc_" ===---cc---"---cc·---·----·---·-<·-

Sumrnarv .

--"---"""----------""--""--"'--,,--------,,.-.,,-~

. _. __ ...... • __ .... ,. __ ,' ... 25ll

x

U rheberrec htl ich gesc h utztes M ate,ia

U rl'~bmreo h II lc hOes" h llie IeS M m~ri~J

fl8 3,Q in

As the small scale enterprises started growing into large scale enterprises, the distributed applications emerges, The distributed applications arc the set of programs run on more than one computer and communicate through a network. Today the developing enterprise level application, which need, to be scalable, transactionaly secure, distributed. Enterprise lavaBeans (EI Bs) are basically server-side components which creating such applications, tJBs work as the BUSiness Layer components. There are some component frameworks like EJB such as Common Object Request Broker Architecture DCOM and ActiveX/COM. We are discussing EJB component. framework in this Enterprise Java Bean is JUSt a part of Java EE specification, Hence, before introducing you fJB, let us introduce you withlava EE 5 specification for its various supported components different types of containers servicing these components.

What is Java EE 5

The Java Platform, Enterprise Edition 5.0 {java EE 5) is a specification given by specifies st.' ndards and rul es wh lc h shou Id be followed when developi ng Java

level applicattons. The main objective of Java EE is to provide an environment to

tier, platform independent, secure, portable and standard enterprise appllcauons. Java of the three different Java platforms. Tile three different Java, platforms are,

a Java Platform, Micro .Edition Uava ME): A development platfonm for the used in Java enabled devices,

a Java Platfonm, Standard Edition Uava Sf): A development platform with core classes and interfaces which CJn be used by standard core applications, Java ME and appltcanons,

IJ Java Platform. Enterprise Edition Oava EE): A development platicrm for lava enterprise level applications. This provides different technologies for the components to be designed for a large scale applicatlon for an enterprise.

The Java EE specification describes standards which are independent of any platform and support> cross platform development and deployment. The Java EE provides a framework for building and deploying various server components. Java EE specification different technologies which ore based on the technologies supported by Java SE.

Java EE 5 Components

Generally, an enterprise application. which has been developed using server-side designed using Java EE environment, is a multi-tiered applications. The whole

divided into different segments running on different locations like client machine, enables application server. and database server, You can see Fig.EJB-l.1 to find how a

appl ication is distributed and running On differe"t locations. ~

2

U rheberrec htlich ge5c h utztes M ateri"

F'g.EIB-l.l

A lava H 5 appllcatlon consists of the different components like Servlet, JSP, .and EIBs. The different classes and interfaces have been provided under Java H specification to Create different Java EE components. Let us explain a java H application shown in Fig, EjB-l.1 lor what is ,*ing d isp layed here.

D Dynanik HTMl Pages: The dynamic HTML pages are the diem-tier components as they are not executed On server -s ide.

D Servlet and java Server Pages (JSP): These ore the web-tier components that run on the server. The Java Ef 5 web tier components are Servlet, jSP pages and pages created using java Server Faces technology. The Servlet is a java programming class which dynamically process requests and generate responses. The Java Server Pages are the text documents, which execute as Servlet and provide a natural approach lor creating dynamic content. The java Sever Faces technology builds on Servlet and jSP technology and provides the user interface component framework lor the Web applications.

D Enterprise Java Beans: These are the business components that run on the server. The needs of a particular business domain like banking. retail or finance is resolved by the business code which is also known as business logic. the business logic is handled by the Enterprise beans running in the business tier, The Enterprise bean receives th e data. from th e client programs, then processes it and finally sends it to the enterprise information system lEIS) for storage. Moreover, the Enterprise bean also retrieves the data from storage, processes it and then sends it back to the client program.

o Dalabase: It stores the data about particular Web application, enterprise or company in an organized manner so that various operations like accessing data, updLHing datil and deleting can be eas il y performed,

The java H 5 Components are written in lava programming language and are compiled in the same way as any program in the java language. The basic difference between the Java EE 5 components and standard java classes is. that the Java EE S components are assembled to form a Java EE 5 application with it.s related classes and files and these commuotcate with other Java H S components, The java H 5 components are verlfled to be well formed andin compliance with the lava EE 5 specification and are deployed where they are run and managed by the server.

3

U rheberrec htl lch ge5c h utztes Iv! ate,i"

£/B 3.0 flO Simple SkI's

Java EE Clients

The I a va H 5 cI rent ca n be of two types - the applicat i On cI i en 1 Or I he web cI [en!. An applicllUO n client is a Craphlcal U~er Interface (GU I) and run, on the cI ient machine, The application clients can directly access the Enterprise beans running in Ihe business lim and can also open HTIP connection 10 create a communication with the Servlet or the )5P page running on the web-tier as shown in Fig.EIB-1.1,

The Web client can be the dynamic web pages containing markup language. like HTML, XML etc. or the web browser rendering the page. received from the server. Sometimes, the web dient is also known as thin cl ien!. The thin clients, instead of querying the detabase, execute the complex business rules or connect to legacy appllcauons. Different lava EE components are serviced by some containers throughout their life-cycle, We have different Iype> of containers wh ic h have described here.

Java EE 5 Containers

The Java EE .1 containers provide the runtime environment support 10 the lava EE 5 application components. The lava EE 5 application component" use services of the Java H 5 container throughout their lil·e-cycle_ Let's learn about the different services provided by the Java EE 5 conta i ners to I he J, va E E 5 a pp Ii cal io n component."

Containsr Survicos

Before rhe web component, the Enterprise bean or the application client component can be executed; they must be assembled in the Java EE 5 module and deployed into it, container, The container manages the services like security, transaction, JNOllookup, and remote connectlvltv, Let us explain them "II.

a 5e<:urily: The Java EE 5 security model allows you to configure the Enterprlse bean or the Well component so that only the authorized users can be allowed to access the system resources.

D Transaclion: The Java EE 5 transaction model leis you to spectfy the relationships among the methods that make up a single transaction by which all method, in one transactlon are treated as a siogle unit.

o INOI lookup: /NOI stands for lhe Java Naming Directory Interlace. The I NOI lookup service provides the interface to the enterprise cllents for accesslng resources. In local or global JNOI tree. if a Java Of web client needs to access the Enterpr'i,e bean component running on business tier, then the client can easily access the Emerpri5e bean by- using the JNOllookup

service, lookup method finds EJB objects that are bound in INOllree. -

o lava EE 5Rcmote Connectivity: [ava IE 5 Remote Connectivity model manages the low-level communication between the cI lent and the Enterpri,e bean. After an Enl.erpri'c bean is created, a diem invokes mel hods on il. .15 if it were in the same virtual machine.

The questio n must have a ri sen in your rnl n d I hat what are I he d i fle'enl Iypes 0 r con ta mers wh ich manage the preceding servlces] Some non-conllgorablc services are also managed by the Java EE 5 containers, The non-conflgurable services are like the life-cycles of the Servlets and Enterprise

bean. - .-'

4

U rheberrcc htlich gesc h (jutes M ateri"

Chapt." 1; I" trodud"8 fIB

Container Types

During deployment the Java H 5 application, components are installed in the Java EE 5 containers. The Fig,EJB-1.2 displays the Java EE 5 server and the Java EE 5 components. As shown in (he Fig,EJB-l.2. the Java EE server has two different containers that is Web container and EJB contalner.

Ftg"Ejll-l.:l

o Web Container: The Web container handles the execution of the web components such as, Servlet and the JSP pages in the Java EE 5 applications, These web components and their container run on the java EE 5 server,

o EIB Container: The E.JB container handles and takes care of the execution of the Enterprise

Java Beam.

In addition to these two server-side containers, we have another container which runs on client machine and handles the execution of the application client: this container is known a, Application Client Container.

After this brief introduction about lava EE specification. its technologies and different containers.

Introduction toEJB

In today" era, the human expectations are increasing day by day. Everyone needs the maximum output but at the cost of least e[fort. Taking the example of real life scenarios. the mode of switching on a televislon with a bunon has been switched over to the use of remote control, washing of clothes with hands has COme down to the use of washing machines,

Si m i1 arly, t he word enterprise co mpr lses a vast n umber of Ira nsa ct ion S Ii ke collect ing. retfi evi ng. reporting the huge data of a large seal" enterprise. (lut when the developer talks about developing an enterprise application, the entire scenario melts down into a simple word, information. The enterprise applications are defined by their need of retrieving and transforming the bulk information. EIB Serves a simpler approach to the enterprise application developers. Enterprise Java Bean is a server-side component (hat encapsulates the business logic of an application. Business logic processes the data entered by user through web components' user interfaces of Web applicatlon, Enterprise beans are the link between the presentation of )'our

5

U rheberrec htl lch gesc h utztes M ateri"

viewed in a

lava fE 5 that Java Enterprlse and deployed in

The t,'Chnology

secure and portable applicatlons

Need of EJB

Generally, EJB is useful in made by using COBRA transactions and enlarge exa mple to expla i n scenario

has small scale enterprise having days passed, the numbe r of goodwill of the enterprise has business. for expanslon, the

In other words, the customers database, a nd can do rna ny level securiry. So, the owner' features which makes it the transactlonlty secute

IIJ Simplicity

The application developer does not have to security. transactions. multi-threading, security resource pooling etc. The", system-level issues of fJB architecture. As a result. the developer

1[:1 Reusability

The Enterprise bean is a reusable component. II can be The Enterprise bean which has not yet appltcanons without, requiring any changes.

Multiple applications can make calls to the deployed enterprise bean. 'IJ Sea lab;'i ty

The fJB application, are highly Scalable" Scalability refers to the rate at which an application can be increased, without any degradation of current

example. if an application is developed to handle 100 concurrent users with After years, the number of users or the number of customers gets doubled. In to increase the current processing capability of the application, with no perforrna nce.

IJ Transacl.ionality

6

U rhebe rr ec htl lch gesc h utztes Iv! aleri a

Developers use transaction concept to provide systems with Atomicity, consistencv, Isolanon and dorability properties, These properties finally leave, database 0; the system at a conslstem 'tate if something goes wrong. In EJB, the transaction management is, left to the EJB ccnrainer which is one of the components of the (JB architecture.

Types of Enterprise Beans

We have created sesslon bean under EJBCla,s toptc. There are also other types of enterprise Java beans, Various types of beans exist, to provide flextbil ity because each company h.15 different type of distributed system. The Enterprise bean is classified into following typ", bawd On iunct ion" I i ty;

o Sess i on Bea ns IJ Entit)' Beans

IJ Message-dr iven beans

Session Beans

Session beans describe task to be done for a client. They hold usually huslness processes that have logics or algorithms. S-ome examples of these business processes are del ivering an order, finance calculations etc. The session beans are also non-persistent Enterprise beam. By nonpersistence, we mean that the using session bean we cannot provide permanent storage. The session beans can be of two lypes:

IJ Statefu I session Bean IJ State I ess sesslo n bea n

StatBful Sossion Baan

This session bean acts on behalf of a particular client, and maintains the client's particular inforrnatton throughout the sesslon. ln order to ~mdef'sl.:md tl more dearly" lers take an exarnple of an Online Banktng, Once the online customer logins with the accouruid and password, the user Can continue with any transaction like amount deposit or withdraw until either the user logs out or the session expire" .AII transactions will be executed successfully, This i, because during the login period of the user, the particular information of it, account_id ls being maintained across multiple transactions. It exist, till the duration of a >ingle cllent sesston, So in this way, the Stateful session bean creates a conversational state across multiple method calls and transactions.

StatelassSessioD Bean

This session bean does not maintain any conversational state; rather they are pooled by the fJB container to handle multiple requests from multiple clients. In other words, in the case of the Single operation, stateless session bean can be used, The,ingle operation can be like mailing, convening the dollars roRs or depositing an amount in an onl inc bank account, The multiple clients can perform any of the preceding operations simultaneously. The stateless session bean handle, multiple client requests, whereas the Stateful session bean takes Care of a single client request.

7

U rheberrec htl lch gesc h utztes Iv! ateri"

£/ B .W in Simpl. 51'1"

Entity Beans

The entily beans are the Enterprise bean which contain persistent data and provides persistent storage (0 that data in a database. By persistence, we mean that the state of the entity bean is saved in a storage mechanism. Persistence can be performed with the help of Java object Serlalizanon and Object Relational Mapping. Second one is latest and currently used technique, lava Object Serialization is done with the help oJ Serializable interface. II, captures the current state of object and 'aves it iOIO permanent storage, Instead of seriallzlng an object, We can break object into constituent component' and store each component separately. For example, Bank account object is divided into bank account number and account bat "nee components. Each component is stored in two different rows of relational database, The entity bean whtch manages persistence itself is called Bean Managed Perslstence {BMP) enlity bean. The entity bean whose persistence is handled by the EIB contamer is called Container M"naged Persistence ICMP) entity bean"

Mess8g~Driven Bean

A message-driven bean is an Enterprise bean Inat allows fava EE 5 application, to process message. asynchronously, In other words, the message-dnven beans handle operations which do not require immediale response. For example, if a user using J website clicks on the button "keep me informed.", il may call a message-driven bean to add the user to company's database. Since there is no need for the user 10 know about the Success or failure, so il is an asynchronous message.

Previous Versions of EJB

We have different versi ons of EI B whi ch co n be used for t he a pp I i co tio n development. The EJ B 3.0 was introduced with Java EE 5 specification. Each time a new' version of fiB is introduced, some new and significJnt changes are included. The different prevtous versions of EIB are EJB 1.0. EIB 1.1, EJB 2.0, and EJB 2.1, The different versions of EJB previous 10 EIB .1.0 are not being discussed in the book. BUI to make our reader familiar with Ihe previous architecture and implementation details for EJB, we are explaining EJB 2.1 here before introdudng you EIB ),0.

EJB2.1

The development and implementation of an Enterprise Java Bean requires creatlon for different multiple interfaces and classe s. These interfaces and classes need proper infrastructure to successfully execute business methods. The EJB architecture is the lnfrasrructure OJ the framework in which the Enterprise bean ts being deployed. The EJB architecture can be desert bed with fa II owi ng heads:

EJS Server

E,IB server provides an organized framework for the execution of the applications that are developed by u,ing EJB components. It controls the allocation of the appropriate resources to the appltcanons. In addition, EJB server provides the basis for the EIB container. lt provides varlous system services like naming and tran,action service. multiprocessing, security, etc, 10 the fJB container.

8

U rhcberrec htl lch gesc h utztes M aleri"

EJB Contlliner

The EJB container that is provided by the EJB server hold, mstances of more than one EJSs. The EJS container handles life-cyde of the EIB and also provides other container' services like transaction, securit)' etc. II serves as an intermediate between the Fnterprise bean and the fJB client, The Enterpri~ bean is deployed in the EIB container, within the EIB server, We have two interfaces associated with our EJB that is its Home interface and the Remme lntertacc. EJ8 contclner automatically generates implementation classes from these java interfaces and these implementation classes serve as a proxy for the EJB client. The client code invokes a business method on the generated proxies which in hun places the method arguments into a message and sends the message to the [1B server.

Enterprise Bean

The Enterprise bean is the component th.ll ts developed by the developer to provide implementation to the business logic. The Enterprise bean is being invoked by the EJB client with the support of the EIB container. The Enterprise bean comprises of two Java interlaces, Home and Remote, and bean implemenlation C1a,~ (01,0 known as EJB class), provtdmg Java implementation to the business mel hods, We will discus> here these one by one.

Rtlmohlllllrllfllctl

The Remote interlace contains the li51 of Ihe business methods whose implementation is being provided in the EIB class. In brief, the Remote interlace specifies the remote business methods that a client can call On an Enterprise bean,

HllmtlllTlfNfactl

The Home interface contains methods for finding, creating and removing the EJ8 instances. EJS Home reference i 5 generated by co nta i ner from thi s home interface.

,EJBCktss

The EJB class provides implementation to the business method deuned in the Remote interface. It uses EJBHome objects implicitly 10 generate Meta classes,

You must have noticed that \0 perform a simple task the developer needs to go through such a lengthy procedure of creating Remote interface, Home interlace and the EJB Cia.", Apart from these, the developer also has to create the difier~nl configuration files. The Deployment Oeseri ptor is an XML forma t file conta in i ng tn e in format ion of I he E nterprlse bean like the name of the Enterprise bean, its type and many more,

EJB Client

EJB client can be simple Java program or web client. Ultimal"ly, user runs these clients to get results. EJB client program uses JNDI service to use the Enterprise boon in its application. With

.~ the help of tne JNDI,- the client is facilitated with looking up and invocation of the Enterprise bean. So, until the client knows how to lookup and invoke an Enterprise bean, the implementation of the Enterprise bean in its application is not possible.

With the hel p of EJ B 2,1, stal,eles, session be" n C~ n act as Web serv ice end point and enab Ie, EJB container 10 implement Web service. These session beans may be ea,ily called by using SOAPIHTTP. In earlier versions, Message driven beans use only Jav,l Messaging Service, Now,

9

U rheberrcc htl lch gcsc h (jutes M ateri a

fiB 3,0 in Simple Step'

MOBs can connect to Java EE 5 connector architecture QCAI message services and also perform messaging by using Java API for XMl Messaging UAXM). tJB 2.1 container also fartlitates limer service to schedule callback actions. We usc EJ6Conl,,,,,t to access timer service and EIBContext provide, needed general runtime objects to Jny tiB. Using timer service, we can ilwoke EJBs at particular time by using event based proces s. In addition, E.IB query language becomes more advanced and includes functions [ike AVe, SUM,. MOD, COUNT, MIN, MAX and ORDER BY.

Still the developers found hard creating an applicaucn by using EIB 2,1. In orde to simplify the task from the developer's point of view. the expert team of EI B came up with EJB 3,0 specification, The new features 01 £IB3.0 have reduced the complexities for the developers,

Need of EJB3.0 (

Development of EJB applications was not an easy task as it became more complex wit~ each release of EJB specifications. Mo"y developers feel th~l developing on EJB application is a nightm""" LeI', summarize the complexities of the previous mood E,IB2.1 here:

IJ The EJB2.1 and the previous models of tiB required the creation of home and remote in terfa c es and the imp I ementation of severe I unnecessary ca lib. ck methods, Th is made a lengthy and complex procedure for the Enterprise bean developers to develop a bean,

o The Home and Remote interlaces r~'qu ire implementation of EJBObj ect and handling many exceptions like C'rea;:eEx.cept i.on, RemoteExcept ion.

D The EJB Deployment Descriptor is cornplex and erroneous.

tl EJB model based On the container managed persistence is again complex to develop and manoge, The basic feature of dct1nir'B a primary key iI, a standard way using database sequence was not present in EJB 2.1,

o Another major complexity of EJBs created using EJB2.x 5pecification is that EJB modules cannot be tested outside an ('JB container.

o EJB Client finds difliCllltly to look up and invoke an EJB. The EJB CI ient needs to know minute clemi Is of JNDI, just to use an EJB in the appllcallcn.

!J EIB Ql is 51i II not so impressive to compel developer to use it. T.ney still use J DBC and SQL or other frameworks like Hibernate for persistence.

New Features of EJB 3.0

The EJB3.0 has addressed these complexities by removing the need of interfaces and Depl.oyment Descr'iptOfs, In EJB3.0, these mterfaces and the Deployment Descriptors are generated by the EJB container, using meladata annotations. Moreover .• the usage of regular Java classes and lntertaces has been provided in EJB3.0. We are describing them one by one,

Annotations

From the developer's point of view, EJB3,O extensively uses Java annotations. EJB3.0 depends on the annotations. Annotation is a kind 01 attribute oriented programming. In attribute oriented programming. programmers mark the program elements like classes, methods. to Indicate that they maintain application-specific Or domain specific semantics. Meladata Annotations are

-10~--------------------------------------~---------+

U rheberrcc htl lch gesc h utztes M ateri"

_ Chapler 1: Introducing E.ja

specified on the basis of Configuration using Exception approach, Configuration using Exception technique helps in simplifying development in several' aspects of EJB J .0. This technique says th a t deve I oper writes code on I y for th i ngs whe re dcla u III ca n not be used, For exa mple, some programmers may define a "validate· anributc and associate "val idate" attribute with the method implementing the validation. The programmer marks the method implementing validation with an eurlbute called "validate". In this way, the annotation has simplified' the EJB development. The an nota tio n s are rna rked with @ symbol an d its use i 5 gi ven here:

In the preceding code snippet, @,emote indicates that it is a remote inwriace.@ symbol used prior to Remote indicate, that it is an annotation, Let's see how the usage of annotations has made t i1 etas k s imp 1 er for I he Enterprise be" n developers. I n I be p rev i ous spec i ficJ lions of the em, the XML Deployment Descriptor has provided information of an Enterprise bean in the following way'

BUI now in the EJB3.0 architecture. the preceding information of the Enterprise bean Can be provided with the help of annotation, like here:

In, the preceding code snippet. the @Stateless indicates that it is a stateless session bean. So. it's amazing that there is no need to write Deployment Descriptor 10 specify properties. The annotations are simpler 10 us", as compared to an XML Ii le_ Also vendors like tBM, SEA has introduced annotations for anributes in vendor specific Deployment Descriptor, The inclusion of annotation, as a fealure of EI133.0, has not only simplified the l.asK of Deployment Descriptor but has a I so s i rn pl i lied the i mpl emen tat ion 01 Co II be ck meth 0 ds.

Callback .Methods

E,iB3-0 h3S also removed the implementation of onnecessary callback methods I ike ejbf'assivate, ejbAclivate, ejbLoad, ejbstore etc. fOI the EJB developers. Earlier if any type of EJB doc'S not require any of preceding methods, still Ihe)' need to be implemented in 'fJB business class, Implementation 01 these methods now becomes optional. Bul if developer defines an)' one 01 these methods in business class, container will call samemilt:hod. Also there is one exception in case of removing stateful session bean Ihat is developer needs 10 use f!lRemove annotation to remove ins tan c e of sessio n bean a he r i nvok i ng busi ness method. Other u sef u I ell a nge in trod uced

11

EIB3.0Iu

by EJ B 1.0 ls I hal an y <) rb i Ira ry m eihod co n be designaled as a ca I' I ba ck meth ad to il i sten cycle events. For exa mp I e:

In the preceding code snippet, ®PreDe,I:roy is the callback annotation. Other annciaticns comprise of PoslConslruCI, P,ePassiv3le and Preaclivale. Some P051Pers isl. are used specl fica II y for en Ii ly bea ns. These ell II ba ck an 0010 tio ns are

in EJ B class or oth er bean I istener cia". In seco nd case, we ha ve to spec ify annotation on bean class to tell container lhal another bean listener class contains Ii fe-cyde ca lib" ck mel hods.

Dupondoncy Injuction Urll nee 111 ell ~~eI1 I I~> B I<J

Th e cl ient, (0 U se th e cons tru cted bee n in its ap p Iklll ion, needs 10 k now how to invoke that Enterprise bean. The client for an EJ B2.' session bean gets the

sass ion bean wi I h J N DI. I n order to use an enterpri se bea n, say Calcu I ator be' n, needs 10 add the 10 II ow i ng cede 10 Toea te and i nvoke on e of meth ad;

In Ihe preceding code. the JNDI name of the Calculator bean is local/remote instance is obtained with creale() method. But in EJB3.0, Ihe INDI CTealeO method invocation is not required. In EI 83 .0, a reference to a resource is dependency in jecf on wi I II I he @(njee! 3 n nota t ion Or th e @Resource ann otatio n.

to conta i n er that lti 5 depe ndent 0 n so me resou rce or aneth er by

injection. EnlireEjB's context made up or container, resourceand environment dependency annotation comprises of type of resource, its properties and its access. In other words, Dependency annotation is a pattern in which the

object creation and the object linking is removed f,om the object dependency injection, the preceding code gets reduced to:

12

In the preceding code, @Inject is the annotation used in order 10 inject the bean named Calculator, Then tha instance named calc is being created of the Calculator bean .. In this way. the use of an nota tlo ns : n fiB 3 .0 ha s s imp Ii fi ed In e task of both developers a nd the E.I BCI ient. Some other examples of dependency annotations are 'IS follows:

CEl,S (naae,'!I!!"" Ses si.onBeanNarie", beanln'te rf.aclE!;oI'se ss i enaean In'te rface. class.) IRlI!!!source (nQle-~,oataba;5I1!!!:Ht ty:pe.Ujavax~sCll.Datasour<e~ cIass")

I:HIS annotauon injeclS stubs of session been having name Sesslonfleant+ame. The @Resource annotation used 10 inject service abied having lNDI name 'Database'. Thls name is present in either glab'l or loca I IN DI tree.

Dependency aonotatlons may be associated' 10 bean class,ils member v"'iables or methods, I nformati a n to be spec i fied .i n I hem depen cis upon the context and I he am c un I of da ta 10 be fetched from that context.

This model slates [hal 'interfaces are not compulsory for entity bean, but Ihey are necessary for session and message driven beans, This line does not convey to developer to define lnterface for sesslo n and me~,age driven bea ns b UI it mea ns that a bea n in te rf ace wi II be ~ener aled of type

or remote accord i ng 10 the ann 0181 ion used in be" n class. Some!.i rnes you do nOI ll ke 10 access to some methods in riB in the interface. Then. in this case, you con create your own bea n j n terface and does n 01 rely upon genera led' bee n in terfa ce as it exposes a II methods.

I )rh b~" .. d I Iv gasohLit. las Bil of Home Interface ano nome UDjeCrS

removed the unnecessary requirement of Ihe home interface. The Home interfaces the home objects have boon replaced by the POlO', and POWs. The 1'0JO's stands for Plain Java Objects and PO)l"s stands for Plain Old Java lnlerfaces. Simple lava Bean is called and simple lava interface is called POJL Previously, when we created a calculator

bean, we had created a HOOle inrerface narred Calculator+iome, Bul now in E)B3.0, Interface has been removed and the same code gels sirnplifled as follows:

notice that no Home inlerface is being defined fat the Enlerprise bean. The lrnplerneotauon [avax.e i b.Sess i on Bea n has "1'0 been removed du e th e u sage of th e an nola I ion @Smlele". class can be annotated by using some other ®StaleJu I, @MessageOriven or @Enlily

13

Elimination of Component Interface

MDreover the business Dr cornponentJruerface becomes Plain Old lava Interface. EJB3.0 has eliminated the Component mterface, The EI BObjectlEJBLocillObjed and the Remote Exceptions which needs 10. be imported in EJB 2.1 to make component interface have also. been removed, Com ponenti rsterfa ce needs to be r oca I Or remote w h i cb ~ II de pends 0 n where busi ness class is located, Ralher. now the POll that is Plain Old Java Interface serves as ~ business interface support i ng ei I her rem 0. te or I oca I access,

The Remote interface which was in EJB2.x has now been removed. The Plain Old Java Interface has been introduced. The code snlppei for the Plain Old Java lnterface is as [ollows:

Now @Remote ls annotatlcn to. generate component interface thai ls Df rem Die type. As a whcle, 'EJB 3.0 elimin~tes the requirement orEla Component interfaces. EJB3.0 has incorporated the use of POjl', for session beam,

Int8rceptors

tnterceptors are methods which i ntercept business method calls Dr lifecvcle callback calls. We can use lrtterceptors with session beans and message-driven beans. Alternatively, we define interceptor methods inside 3 separate class called interceptor class, Interceptors provide us way to enhance business methods with extra functlonality. Fo.r example, Validation of parameters to be passed to bus i ness rneth ad Co n be do ne by usi ng interceptor meth ods, More tha none interceptor Can be invoked on one EJB in the form of chain, We use @tnterceptors annotation 10 lmport chain Df interceptors associated witb the bean. We can define interceptor method, using @Aroundlnvoke armotation, Following (ode is used 10 add interceptor methods 10 bean:

Slri ngScrv ice Bea n sessio 0 be. n is of stater u I type and intercepts methods of Met hod Profi I er interceptor class, The name of the generated remote interface for this session bean is Stri nsServ ice RemDte.

Java Persistonce API

The Enterprise application, have a need 10 collect VJSI amount of mlcrmatton. The long term storage Df this vast inicrmation has been simplified by Java Persistence API. The flrst release of Java EE 5 lntroduced entity bean as a solution to. Ieva Persis te nee. The introduction of Ine entity bean has prevented the developers to directly deal with the persistence. But the flrs; release of

14

the 1.~'(;hn(>108Y lacked many fe~turt'S and provoked many problems to Ihe developers. Some of the major problems were like relationships of the entities which hod to be "'''J1aged bl' I.he applications, fO,",ign key field, were required to be stored and managed 011 the bean class. The EJB2.1 specification solved maoy of the problems by introducing the idea oi container managed entity bean'S. In the container managed entity bean, the server was responsible tor gener4),ting subclass 10 manage the persjsteru data, This EJB2.1 specificati[)n also imroduced the EnlL'fprise Java Bean Query Language (tJBQl.i. [JI3QL is a query language designed to create queries for CMP entity beans. It is similar to SQL bUI searches fo' persistent attrlbutes of enterprise Java bean.

EI B2.1 specification, despite of providing improvements. was still overloaded with the major problems and complexities. The fJBJ.O provides new Java Persistence .API. which simpl ifies the progra m mi ng model for enti ry persi stence. Now Ob jcct Rela tiona I Mapp i ng or Pers istence appro" en uses PO 10 model instead 0 i abstra CI pers is te nee "hem a model. Th is rna pp i ng used to map entities and their relatlonshlps to eppllcatlon' database. EJB 3.0 entity depicts persistent lrucrmatlon stored in database using Contalner M,nagcd Persistence lCMl'i but tlB 2.1 entity bean only represents perststcnt information stared in database. The optimistic locking technique earlier only supported by TopLink persistence framework is also encapsulated in EJB 3"0 specificaHon. It also enhances R/llV access ratios. This locking a How to use objects in disconnected model which means changing data and their relationships offline and merg" data operation, into one transaction. Optimistic lock value tells us changed copy of data f, not stale. We can also create deep and wide entity inheritance hierarchies. Other additions and subtractions made in the J"~V.1 Persis.tenC'~~ API1 which were not there in F.H12.1, are as io[l[')w~:

D It requ ires less n u mber of cla so", and j nterf aces.

o New E nt i tl,Ma nager A PI s im i la r to H ihernate ls i ntrod u ced 10 perf orrn ope," I ions I ike

creation, removal and 5carching on enri!)' beans.

a The Icngthl' Deployment Descriptors have been eliminated through annotations. D II. provides cleaner, easier and standardlzed objecHel'Miorl,,1 mapping.

D The need for lookup code has J IS(> been "I i min" led.

o It adds sup port for inheritance, polymorphism, and polymorphtc queries. 1:1 II adds SlJ[lPOr1 for named (stallc) and dynanuc qmlrif"\.

1:1 We ca n now perform man), d" taba sc re I 0.1 cd ope r ,11 ions i nstead of on I y one ope ratio n generaling primary key in EI B 2.1.

IJ II provides a Jav,1 Persistence query la"gu"B('-<In enhanced EI B QL

a It makes easier to te~1 entities without the EJB container, Earl ier, developers need 10 be aware of deployment platform 10 test 'J(ls.

The crux of the new Java Persistence API has been listed earlier. In detail, il would be explained in the later chapters.

Summary

This chapter starts from structure of enterprise applications and describes Java F.E 5 platform w h i ch is used 10 develop these enterpr i se app lie al 'i ons, It j nl rodu ces J" v a H', compc nents ll ke

15

U rheberrcc htl lch gesc h utztes Iv! ateri a

un J.D in S;."pI. 51,,!,>

Servlets, .IS? "nd EJB and it, all types of contalners with their services. It also discusses requirements for introducing EJB te<:hnology. We have also discussed EIB 2.1, its features, various types of Enterprise beans and EJB 2.1 limitations. Finally, we have explained you to how latest version 3.0 01 EIB overcome limltatlons of fIB 2.1 with its new features like annotations, dependency injections, POlO tebniques and simplifies all aspects 01 development. tn next chapter, we will t.ake you to the development of session beans in EIB 3.0.

16

U rhcberrec htl lch gesc h (jutes M ateri"

U rh eoerr echtlc h gesChnlll es B lid

fIB J,O i"

Introduction

Before getting into 10 the details of session bean in this chapter, lct's flrst discuss about what beanl You must have heard of the term 'Java Bean' in Java. In a simple' words, Bean can defined as One of the reusable software component, and a number of beans Can be

logel.h er 10 form an H p p'l.i ca I ion, A J a v ~ Be ~ n i. 3 regu lac I a va class thai has setters and methods to provide access to its state andEJ B is a regular Java class that nasa, method

logk inside it and provides" remote interface 10 achieve the bean logic and the home

wb Ie h actua lIy creates th e B ea n. J a va Be a n S are the non-sha rable components that developed and run Within a single system, whereas EJB is used in a distributed environment can be shared across system. The main focus of this book is on EIB; so, let's go for.

di 5CUSS ion reg. rdi ng EJ B.

The enterprise level applications are entirely based' upon the business logk and according concept, the term EIB is also related 10 business logic. ln the previous chapter. we have discussed the concept of tlB and different types 01 EJB i.e. Session bean, En~ty bean Message·driven bean. Here, in this chapter, we are going to discuss the concept of

in detail with us full implementation through examples. .

Concept of Session Bean

The term Sesskm bean has coined using two words l.e !€Ssion and bean. The

That. the bean instance is a v eilable for a particular duration of a unit. of work and it

after that. which mean> that its lifetime is within a specific duration. A Session

defined as the reusable componeuni~50rroctiiliCh Q~lciiiJdes '1:0 business process and works on behalf 01 the client code wrucn mvoxes ·,t, so, a session bean represents a 'single ins ide I he Appl lea I i on serve r wb lch:

o Does not maintain the state of cl lent,

o Does nOI represent the data in data store.

S ess ion bea n is not persistent a nd hence it lives for " short period and ends. up its I i Ie server stops. Now I he qu est i on cernes- '" h en to use' the session bea ns 1 sess ion bea ns are su i ted lor the bus i n ess P'O<::e>$ 0 r fo. I he co ruro I logi c that exh i bi 15 rnu Iliple e nti ly bea ns reflects from the Fig.EJB·2.1 also,

session

18

The two important issues to be discussed here about Session bean are lts lifetime and its subtype,,_ Before going to the ,ub-Iype, of a session bean, let', r.rSI find OIJl, about the lifetime_ As we know session bean work> on behalf of a client, so as long as the client is there, the instance of that particular session bean remains alive. The time period between the client acce5sins an instance of session bean, and the client calling to remove to end-up the life of the instance of session bean is known as a session or conversation, The state that is majntained from the initialization or a session bean 'instance to the destruction of [hili instance is known as the conversational state, So, the lifetime of a sesslon bean instance is equivalent 10 the session of the client. There are two main aspects ollifelime that must be I,aken i"IO consideration. First aspect is Ihat a ,ingle instance 01 a session bean i, never shared between different cI tents, So the length of ~ conversation is measured by the lime period in which the bean instance has been in use, The second aspect of the lifelime tells that the container is in control of the life-cycle of a session bean's instance, so whenever any timeout occurs, the container can remove the instance. Now you can consider from the two aspects that Session Bean instance are not persistent, it mean, their state ls not saved into persistence storage I ike file syslem or a database. After understanding the concept of the lifelime, now it's rime to get into the detail, of sub-parts. Sub-pari is tOlally dependant upon the conversational state or the lifetime, Whil" a conversation is goi ng on, whal exactly happen, is that the client calls the business methods that are defined by the bean instances. A Session bean mal' fall into one of its IWO sub calegnries considering the fact whether the result 01 the previous conversation is saved or nOI. The two subtypes of session bean such as:

Q Staleles, sesston bea n a Statclu 1 session bean

'Slaleless session bean', the name itself indicates that the bean i, slate less, which means without state. This bean does not maintain any state, whereas the 'stateful session bean' indicates that the bean is here maintaining astate. In case 01 stateless, whenever il executes a. request, il returns J result without saving any cllent-speciflc state information whereas in case 01 stateful session bean. il saves the rhent-specllic tnforrnatton. St'C the following sections for details about ihese two types of session.

Stateless Session Bean

A stateless ,,->55;On bean can be defined' as a bean that contain, the conversations, that exhibits a single method c311 but it doe, not save any conversational state Ihilt 3 user performs. The container may wish to destroy the bean's instance itself after the completion 01 the conversation or ;t may use the instance ag"in. for some other requests that are generated by differenl clients. Here the bean instance <IDe, not remember the information about the result it has calculated. lei's take a" example for the better (Jnder~landi"g of Inis stateless sesslon bean like onl ine result verification, here the user is supposed to enter the roll number or tne registration number and JS soon as the lorm is submitted, a bean instance is created and forwarded. to the server for the respective response. As soon as Ihe server get> the resuh.st sends this result a, respon", for the given req uest. Once the resu II has been suppl ied to ih e ca ndi da te, the bean f orgets abollt a II th e supplied information, Aft.er this, when another candidate ,)gain enters his roll number to gel the result, J new instance is created, So, even if the !'irst user wants to see his result once again then

19

U rheberrcc htl lch gesc h utztes Iv! ateri"

fJ B J. 0 it! Simpl< 51<1"

also he has to provide his roll number again to get the desired information that speclflcallv

di spla ys h lsresu It. .

Another con cept regard i ng sta ieless session bean is pool i ng. St. teless bea ns define pool ing in fh ei r I i fe-cycle. In co se of th i s state I ess session bean, a II instances of the same bea n are eqcivalent and not distinguishable to a client. As a result .. a bean inst.,nce can work for any cl ient as they .11 are same. 50, we can say that stateless session bean can be pooled, reused and swa pped from 0 ne di en I 10 another cI ie nt On eac h method ca II.

Stateless sess ion bean I nsta nees ca n be pooled a nd may be shared between d liferent cI i ems. When a client invokes a method in a stateless bean, (he coruainer either creates a new instance in the bean pool lor that client or assigns one from the bean pool and that instance is again returned to the pool after use. So, we can conclude that pool 01 bean instances are created by the container at a particular time. This may occur when s)'stem boots or when the size of the pool becomes too small. Bean instances are then recycled according to the number of client's use. Hence, srna lie r n umber of i nsta nces can serve a large nu mber 01 cl i en ts at a sing I e lime.

life eyels 01 a Statslsss Ssssion Bsan

Th e I ife-cycle of a state less sess ion bea n ca n be described with va rtous methods wh ich are invoked throughout its life. A Stateless session bean can be in one of tim following two states:

n Does not Exi,t

1;1 Ready state

The stale of a sta I eless Se55 i on be. n can be cha nged wl th th e i nvoca t i on 01 d ilferent methods I ike ejbCre~ te I). and ei bRemove () etc. You can see rig.EJS-2.2 which represents the life-cycle of a stateless sess i on bea n.

setS e ssi 0 nCo nt ext 0 ejbCrealeO

ejb.RemoveO

Business Method

I'IS.E/B-U

20

In the whole life-cyete of a stateless session bean, we Can see two major transitions in its state i.e, Does not exist state to Ready stale and from Ready state to Does not exist state. let us explain these transitions in brief with different callback methods associated.

Moving from does not Exist state to Readv state

There are some callback methods responsible to change the state of a stateless session bean from does not exist state to ready state. These methods are s e tSes s i oncont ext (I and ejbCrea t e (I .

t:I s.at g.as s Loncon t aa t (). when the EJB container creates a stateless session bean instance and places it in the ready pool. it calls the callback method setSess roncon tex ~ I). This method contains the rcierence to the session context, The main purpose of calli ng this is to associate your bean with J sesslon context because session context behaves as. the gateway to interact with the con ta i ner,

Q ej berea t e (I - After the callback method 5·" t Se e.s i.oncon t.ext. is called, the EJB container calls the callback method e j bCrea t.e I) to initialize the beans. This is important to remember th~t ejbCreate I) method is always called after the set Ses sionContex t () method. This ej bCrea te method is only called once during the lifetime oi the session bean,

When the bean instance is in the ready state, it can service a client's request. It invokes the business method and the fIB container assigns an avatlablo bean instance to execute the buslness method. Once the execution is finished the session bean instance is ready to execute the business method,

Moving from ready state to does not exist statll

Suppose (here are a few- requiremems of session bean instance and your container is having a vast number of instances, then the fiB container may decide to reduce the number of session bean instances that are in the ready pool. To do this, it call, the callback method ejbRemovc. Using this method, it invalidates the reference to the bean instance that is in ready pool. tt doe, not indicate that the bean has destroyed; it only sets the status 01 bean instance as an inactive one.

Elements of Stateless Session Bean

The implementation 01 a. stateless session bean involves development of different components. So before developing an appllcatlon using stateless session bean, you should get faml llar with the following components:

'0 Bus i ness Interlace

'IJ Bean Cia"

Let's So for a discussion of these components one by one.

Busin IISS Intllifilce

An interlace through which a client is able to access a bean is known as business interface. Generally this interface contains the bean methods that are essentially required for developing bean related applications. The methods declared in business interlace are known as business methods. This interface is necessary for the stateless session bean, The business interface con be

21

U rheberrec htl lch gC5C h utztes Iv! ateri"

EIB 3.0 i" Simpl.51.1'<

of two type, i.c . Jocal mterface and remote interface. The type of J business interface can be defined by u.Si,ng armoratlons like @Remote and @Loe,de. If you will not provide any annorauon, il wi II take it as local business lnterface.

Bean Class

A stateless session bean is represented by a class known as bean cia" which implements some business interfaces. This bean class can implement multiple business interfaces, A stateless session bean most be annotated with (he 'GStatdess' annotation or should be denoted in, the Deployment Descriptor as a stateless session bean. This is why, this bean class need not to implement the j"vax. "':lb. SessionBean interface as required in previous version of EJB.

No/.

OBVB/Opillg 8 StatB/BSS SBssioll 88811

Now let's develop a sample appl lcatlon by using the stateless session bean. Here we have given an exampleuslng siateles session bean that is quite similar 10 a simple "Hello World" example. See the foil owi ng step s fOJ deve I opi ng thi' si mpl e a ppl i ca ti 0 nan d ~ nd how a slate less sess i on bean can be implemented.

Crllating Business Inlorface

T he rea I fa CI be h i n d th e creati 0 n of 8 busl nessl nterfa ce ls:

CI Thlsiruerface defines (he diem view of the bean.

o The busi ness in tc rfa ce dccl a res a II the bu Ii ness m ethods,

The busl ness imerfaces created in this example has been shown in Listing 2.1. The name of this lnterface is Hello and the only business method declared here is String hello (I.

listing 2.1: Hello. Java

structure where we have to save this file is given later in Ihis chapter.

N<iIt.

Croating Boa n Cia ss

T h i I is the second req u i red class for I he state I ess sess i on bean imp I erne ntatio n here. Th is bea n class II simply a plain Java cia" which implements the busl ness interlace, defined in the

22

bustnessinterface. This bean class is also known as the implementation class of our stateless session bean class as it provides the implementation to "II business methods. The HelloBean cia" is our bean do", here which implements business interface Hello (Created in Listing 2 .. 1). You can see Lisling 2.2 fo, the code 01 He 11 oacan ctass.

Listing 2.2: HelloBean.:l ava

Store He 11oBean. java file in the same package as that of the "1·lello. j "V,," file i.e. in 'ex"mple' package. A stateless session bean must be annotated with the stateless annotation '@St~tele s s: or it is denoted as a stateless session bean inside the Deployment Descriptor. The magic of the EI63 is the use of "annotanon". tr's the annotattcn "@Stateless', which clarifies the bean as a sratel e ss session bean. In the preceding Listing 2.2, we have used the annotation 'e S ta teless' to specify the bean as a stateless session bean. The main goal of introducing this annotarlon EJB 3,0 ls 10 reduce the efforts in creation of different components and their configuralion applied e~rl ler vvith tile previous versions of EI S,

Creati ng Client

To access anenterprise bean, a c.I lent code starts its execution by using the JND,I Uava Nami,ng a n d D i rectoryl nte rf ace), Til isis needed to obt a ina di reel ory COn n ect io 11 to a bea n's COn ta i Mr. Do not bother abOUI the word JNDI. I! is an API for directory service that allows clients to discover and lookup data and objects via" name. The code used 10 obtain tile JND.I context depend, upon the Appllcatlon server you are using. See the liMing 2.3 for the client clas of this applicaucn, Here we have used a J5P file as our client. No doubt )'OU' can use the lava ii le also .. listing 2.3: hello. j sp

23

E)83.0;"

Urlleoorrechll ell g~SCI1ULZ1B' Bild

Save the cede shown in listing 2.3 as 'hello, j sp" in the directory 'web', which is inside the 'Hello' folder, Once the connection is estabhshed, and the context is

the 1 n i ti a ic '" n t e x t () method, t he con text can be u sed to look up the ·EIS' 5 home the lookup () method. This ;5 why, we have writter, "he l ( ct.x .Tookupt " j a ve : comp/ e nv I ejb/He 1101 He 11 o Se an") ": Here the "hell o . j is looking for the home eta" that is 'Hello. j eva' by using the lookup (I

ha.l Lo.. j sp paBe give, a text field and a submit button. You can eruer some name in field and cl ick over the submit button 10 see Ihe suing returned by business mel hod hello I String).

N.t<

24

U rhcberrec hthch ges c h lilltes M a erla

Or(Ip/~r 2: Session B.el!'1

OJ reeta rv Struc:tu re

Begin by giving a name to yOUT main project ", 'Hello'. Under that create three folders, such as 'EJ!l', 'web', 'META~INF'_ The EIB folder and the web folder are also known as the bean module and web module respectively, Inside the EJB, directory keeps all the Java files like interfaces and bean fi,les that are inside your appl icauon. And inside the 'web' ai, rectory, keep all the )SP files, html flles, META- INf fi le always comalns the MAtH FEST. MF file by default; here Ihe only addltlonal element you have to keep ls 'application. "ml'. This file ls necessary for the EJB3 applications, See the following Lisling 2.4 for the configuration provided in 'applic.at ion + xm'l ' file.

LiSling 2.4, appt i ce cion. »ml

on. xrn'l file configures two module, used in our application, The names of two are web and ejb.

The structure oi our "Hello" project will 'look like as shown in Fig_EJB.2.3_

25

f./B 3.0 in Simplt SI<p'

a-b_ 6~ .j,

'I 8-~ ."'"'1lI.

I ·1 t~ :::::'dMs

i B··~ i'EllrI~

I i L.I!} .MAMlF£5T."" 8~ sr<

(.ij] fiollo.jOvo

j ......... ,Hi:~,i4..;!!!

(~H'!) fo£T A:UIF

! ~.1i1 Ofd~,"'" ! ,_.l!l MANIfEST."" 8~el-...t>

I i3-e WE&-.lN'

[i I l._."~~. h:1

. Ii """'."" [i;i! m)'<tjoto.",

-.j!) HeIo .eee

Structum of Bjb ModultJ

Ail the bean Iii es like 'He 110. java!. 'llellollea". j eve.' in this application are to be placed inside [he e j b folder. As we have defined the 'example' as package name (See Listing 2.2 and listing 2.3), so create another folder named a, 'example' inside the ejb directory and place class fil es in it. The infrastructure of the beans directory will look like a, shown in the

Fig.~B-2.4. .

B-'~ ejb

a-EJ .,""",_

i H::1 tJejkl.cJass

I !.....h'J HelIoIIe.",daH S .. f!) 1oUA-1'"

i L~ MANlfEST.~ e-() src

r' ill Hello, )4va

~. ~ HeAoIIeon. jav.

Flg.EIII-1.4

In the stateless session bean, there is no requirement of META-IN. folder in the ejb module, this will be required further in other application, in this book.

StroctunI of Wt1b modu/s

All the JSP files, HTML files are placed inside this directory, The hlerarchlcal structure of thls web module is as given here in Fig. EIB-2.S.

26

U rhcberrec htl lch gesc h utztes M ateri"

CI'"l'lcr 2: 5<S5'O" Be""

------- -- -----

8"'(~ web

i 8"~ WEHNF

classes :'.,.~ web.xml

hello.jsp mystyle. css

f;g.EJD.2.5

The coding structure or rhe web. »mj, Ii le of WE;B- JNf is giverl in the LiSlirlg 2.5, Lisli ng 2.5: .we b . xml

it sure that all components created are pieced al the right location according to the structure shown in Fig EJ6·2.3.

completing the development or all component', we can discuss how 10 deploy this sample with I,he weblcgic server.

Hllllo.llllr filII

lime to ere-ale- <in . en r me through rile command prompt by using the command JIoj a" • ear ••• " by staying in the 'Hello' directory Ihat is in the main project folder. have given the ear f;le name as 'Hello'. By doing this, all the funct.ionality thai is inside the EJB module like HETA-INf, as well as in web module will be included in the file. Here )'OU must be I h in ki ng abou I I he pass, b I C rea son behind ge nerati n g an This is SO because here we have used the weblogic server for the deployment for which we need an . Me type of file.

27

£/B 3.0,,, Simple Skp'

Oep/oymflRt

For the d~p[oyment of this app[ ication, here we hove used Ihe weblogic server 10. You can "IS{] use any other EJ B3. 0 en. bled Appl icat i on server [a r I he dep loyrnent of I h e a pp [; ca I;on S.

The steps for the deploy men I of EJB appllcation through w~blogic 10 are given as 10['lows:

1 Starllhe server.

2. Open the browser and write ''http://localhost : 7001!console" on the address bar.

The login page lor the web logic server console will open.

J", f nle, the a pprop r i ale Username an dPasswn rd in the logi n screen and press en te r.

After giving a valid usernarre and Password, )IOU will find you, weblnglc browser "5 shown in Fig.EJB-2.6.

U rneborrec htllch qes c h utztes Bild

Hg.EjU.2.o

4. Click on the Lock & Edit button that i., present at the top-left 'ide of the panel as shown in Fig.EJB-2..6, to enable modification, addition and deletion of items in the domain.

5. Click on the Deployments option of the 'Domain Structure' present in the left panel of the browser as shown in Fig.EJB-2.7.

28

U rheber reo h III h g sc h utztes Maieri a

Url1oher,"cnll eh gesch 11:185 B I~

Fig.EJU.2.7

After clicking the Deployment link, the screen will look like as shown in Fig.EjB·Z.8.

urneberrecnu Gil oescturtztes 8, d

Fig.EJI;.2.8

29

Ur~cbmr ch II h ll~schljt I 5 Ma' riar

EJ 8 3.0 ill Simpl. SIcp,

You will see an Install button On the right pane meant for locating the . ear file that is needed for the deployment.

6. Click the In )tion5 for browsing

your cortes]

Urhoi.Je rcchll ell g,>sch 'IZ as 61 t

7. !.OC.1te YOUi clicking over lin ks

provided, starting with tccathost. ~or example tocalnsot-ot; LJrive->some folder and so on. Sec Fig.EJB-2.9.

B. Click the Next button afler ,elecu'l1g your .ear file. Here, we hava used Hello. ear me as shown in Fig.EIB-2.1O.

Utlleberrochlrch gaschuillos Bid

t 180. tJ U-Z.I U

30

lJr eberrcch uch g schu ztes MeI'erlc)

9. Again dick Next. you will find screen 0, shown in Fig,fJ B-2.!1.

Fig,t)ll--Z.11

10, Again proceed forward b), clicking Next Here yow wilt be prompted to keep J ''''')lC for the deployment ,kecp this name sirnslar 10 your . car file name) c1' shown in the l'ig,:I'JB.2_"I2.

"_d'!.l·PJr'iI'!II'-ori''''~ r~;IJ:'r"T",C'wIljilil~W t. O;-~~"""i!Qnl-.J .... "...q;I~Ll;'=-' Q~ ...... I),I~~lIl1.:":.l""

-~'.':~ ..

'""-~~

~~~

(Io:flo:y_~ ¢,$If.i3jd.

SIrlv':!j,<')C ..... !l-Ig_...-.:c-'~ ;JL~lL:I

~';I~_=:.~-q;; ~~(Fiwv~ W.:'i9f.i!"I~~prw ;o.;~IU'ffi

fi);.~r8-~.1<

11 Now click on Finish button [or the deployment of the ear f 1,,_

31

U rheberrec htl lch gC5C h utztes M ateri"

3.0."

Now res the time to activate

12. Click Acti va t e will not give any

that you made in the webloglc server

your

U, 1 bcrr ,II iell s Chillies Sild

Fig.EJll-2.13

I f you ha ve ca rri ed 0 ut you r dep loym ent su ccessfu lIy 1 hen you will be 5 h Own a cha nges have been act iva ted. N (I restarts art' necessary. 01 herwise you wi 11 fi nd indic~ting the unsuccessful deplovrneot of ear file.

13. Select your recent deployment shown with name Hello ISee' Fig.£JB.2.13) in Deployments section

14. Click Servi cl ng a II requests of th e Sta rt optic n to stan servlc ing a II requ ests as Fig,.EJB-2.14.

32

Now you will be prompted whether to start the correspondlng deployment or not as 'shown in Fig. EJB-2.1S.

15. Click "Yes to send the start request (See Fig EJ 6·2.15).

Urhebarrechlllch gesohuilies Bi d

33

U rheber reo h III h g sc h utztes Maieri a

Afler performing all operations, you will see the message Slarl requests have been sent to the selected Oeploym.ents as shown in the Fig.EI B·2 .16.

U rheberrec 1111 '0 h gesc h Jtzrcs Bid

fig. EJ B·l,,16

And you Can notice here that after all the successful operatlons the state of thej-tello.ear fil'e is converted 10 Ac live, Tb is noti i,i es I h<J t you, appl ica I i an is rea dy lor execu lion. To ru ni t, open the browser and wrile http; Illocal hos t : 7001/ Hello_

H~,c 'Hello' I, the context path defined inside the app.Li c at.Lon cxm.L" a <context-root> element present inside' tile META-INr folder,

After providing the proper addressin the address bar of your browser, you will find the output as shown in the r'ig.E)B.2, 'I 7.

34

Now enter your name in the provided text box and click on the Submit button. You will find your name in the page that you have entered, Suppose you have entered Y(lur name a, Rupali, then you will see the output as shown in Fig.EJB-2.18.

fig.E/S.UB

Remember that this program is for stateless bean. it doe, not store any 01 the state, So, even if you have entered your name once and if you wish to see your name once more then you will have 10 enter your name agaiin_ Now we will move ontothe concept ni statef .. .:d session bean,

Stateful Session Bean

The Stateful Session Bean, the name indicates that it is a session bean having some state, It assures that the conversational state is maintained throughout the session. This is the main aspect which differentiates the stateful sesslon bean from the stateless session bean, In this case, a bean is supposed to be designed to service the business processes 111"t exhibits multiple method calls As the bean is designed for servicing multiple requests spanning multiple methods, so it SJ\le5· a conversaticnal state for each client. Here in this case, for each client, a different bean instance is created and it services the request. The main iearures oi sialeful session beans are like;

a The state of a stateful session bean represents the conversation between the dient and the bean.

a The; n sta nee (If the boa n conta i ns th e inform" li on abo lit t he cI i ent across I be mel hod ca II s. t:I The statelul session bean ts somerhmg like the one-to-one mapping,

35

U rheberrec htl lch ge5c h (jutes M ateri a

C~I",.I;-l'

Client-.}

fi8'Ej1!,:!.l9

In Fig.EIB-2.!9, rhe bean instance "instance-t " is created for the client-t, instance-Z is created for dient-2 and instance-] is fo, client-J respectively. There are no such permissions either 10 the chent-z or to client-J 10 access the bean instance of the client-I that is "instance-!". Similarly in case of client-! , it does not have any capability 1.0 use either the instance 01 the client-2 O. the instance of the client-3. There is a bean instance reserved fm each client and each instance stores the stale in{ Orm. I ion of t h eir respec live eli em. The I ife of bea n ins ta n ce exists u nt il il is removed by the client or limed nul. Better to lake an example of 'online job searching' to understand the statcful session bean. Suppose you have an account in a job site, let it to be 'jobslte.com'. When you want to log on to the site, you need to provide your valid ID and password. Now only you can enter inside the site. When yOll log on, it generates a specific session id for your ID only and with lhis session 10, you are able to visit each corner of the 5ile_ You may want to update your resume that you had submitted before, or mily want 10 search some job' in different location. and ohm that you may select some job, to apply them. Let us find out how it is done. In the 5ite, you do not require to enter your tD and password lime to lime lor each operation, The site is performing oil the tasks that you have chosen, 011 behalf of your account only. You arc not given the permission to access any other account except your own account. 5D by one time logging_. you are able to perform milny tasks in your session. And after completion of your tasks, when you are signing out your account, your session exptres there. So il maintain, " state during the conversion frum the s'igning in time to signing out time. Other good examples of stateful session beans are 'online shopping', 'online banking Ira nsacuon', 'and II i gh t t icket reservati on' etc.

In all of preceding examples, the application needs (0 implement. the stateful session bean as it is necessary 1.0 maintainstale, while the use, wants to work on these.

life Cycle 01 Statelul Session Bean

The life-cycle of the stateful session bean completes through Ihree steps, such as; I:l Doe, not Ex ist S~l te

o Ready State

o Pass ive St.) te

36

U rhcberrec htlich gcsc h (jutes M ateri a

In the Does not hist. state, the bean instance ,imply does not exi,t. In the Re.)dy SlOle, the bean instance is lied to (1 particular client and services the conversation and in the Passive Stale, the bean instance is passivated 10 optimize the resource uti llzation,

The different types of transitions as well as various methods those are available inside the lifecycle of I he Sta lef ul session bea n ass how n in F i g_ EJ S- 2 _2 0 are d tsc ussed here,

lime«.Jt

setSessionContex:t() .per.oleO

cibRcmo"cO orl~eOUl

Moving from "does aot existstate" to Ready state

This state [5, similar to the stateless session bean, When there is interaction between does not exi,! and ready slate and the motion is from does nol e,iSl stale to ready state, it performs tWO differenl types of mel hod, such as:

o setSessionContext(J

u ejbCreate (J

The funcrionalitv of both setSessicnContext (I and ejbCreate I) is similar 10 those, described in the stateless session bean section.

In the ready state, the Stillelul session bean. instance gels involved wuh a parlicul,lr clrent for the duration of their conversation. Duritlg this conversation, the instance can execute the component methods invoked by the client.

Activation and Passilllltion

This is addltional stage which is not found in Stateless session bean. Before going to depth. let's

firsl understand "what ls activation and passivalion1" -

Suppose the client is not invoking a bean for " long time, it is nol " good practice 10 continue keeping it in memory. Here to save the memory, the user employs the process 01 passivation. What exactl)' happens in passivatlon is, it saves the bean instances thJI arc no longer used mto a disk or in some permanemstorage devlces Jnstead 01 holding it in memory. The container performs thi, tesk by serializing the entire bean instance and moving il into permanent storage

37

U rheberroc htl lch gesc h utztes M ateri"

£1 B .1. 0 iOJ Simpl., 51,'p'

I ike database Or J file. Activation is the opposite of the passivation technique. The activation technique ;5 required when been instance is needed again by the client, The container activates Ihe bean iflSI.~nce by re!rieving ,il from the permanent storage, and then deserlalizjng it and sending it back to the memory lor the future use. This process is known is Activation.

The EJ B container migllt passivate on inactive Stateful session bean by moving it irom the read)' state to the passive 5la!G. \'\!h('m a session bean instance ls passivated, its data ~s, 's.eriallzed and wril!€FI to a disk. To perform these ieatures, the container calls (he callback method e j b Pe ss Lva t ct), After passivation, if the client wants to continue the conversation by invoking a business method, then it needs to reacttvate the session bean instance JgJio. lts dJta stored in the disk is used to restore the bean instance state by colling the callback method "jb/\cti"~r"'O,

In the passive stare. the bean instances (In. be categorized into M'O such as:

Q NRU CI LRU

Now you most be curious to fitld out about NRU and LRU. These are some algorithms. The NRU (Not Recently Usedl algorithm lists the items which are not used recently whereas lRU (teast Recentl), Usc"';) algcrlthm is used to list the item thai ls used least recently. So in the passive state, if the Stateful session bean i5 ~t up to use NRU algorithm, the session bean can perform the time-out operation, It means the IUptime of session bean has expired and it moves to the "doe, not exis: state", here it need, to call the method e j bRemo"". But in case of LRU, if a ,t.atdul session be~n is SN up to usc the LRU ,1Igorithm, it (annat lime out while in passrvated st ,)!C "

Moving from the Ready State to the Does not Exist State

Now it', the time to call the remove method in the life-cvcle 01 statelul session bean. When the client completes ilS task and logoul from the appl lcation, the lifetime or his session expire, there:

Here the client application invoke> a remove 'melhod. terminate, the conversation and tell, the EJ B coruainer to remove the instance. He/C, to perform this task the container need to call the fu net i on o j bRcIT.OV c.

Developing a $ta/eful SfJssion Bean

Similar 10 stateless session bean, srateful session bean also uses the bean class, interlace and client class 415 well,

Hem we ha ve gi ven a ca r1 exa mple, where the user i 5 ab I e 10 insert items into cart. Atter insenion, 11e is ab)(, to obtain the new item inserted as well as the previous items, For the complete application, follow the \WPS gi"",n her".

Creating Business Interface

Similar to Our statelesssession bean irnplernentation, we have to create business interlace here too. The business interfaces created her" i, created as remote using @Remote annotation, List.ing 2.6 provides the code our remote business interlace Cart which declares three business methods i.e. edd'Lt em (J, r emcve Lt.em I) and getItems {). This business interlace is being developed here to lmplement ,l Shopping cart.

38

U rhcberrec htl lch gesc h utztes M ateri"

Listing 2.6: ca r t; • java

U rh eberrac ml 0 h gcsc hutz tas BllrJ

Save the preceding code as Cart. j av~ inside the package 'example' of ".IB module. The d i recto ry structu re is ,i mil ar to the S tatel ess bean as d i 5CUSSed in th e p revl 0 U5 sectl on. The on I y difference is Iha\ here the main project folder name is 'Cut'.

Creating Bean Class

We need a bean class here which implements Our business interface Cart. for all the business methods declared there, The code 0; stateful session bean irnplemenration class has been provided in Lilling 2.7. The @Stateful aorotauon defines that the session bean created here is Stateful.

Lisling2.7: Ca rtBean. java

U rh eberrcc htl c h g escnotz tes B lid

39

Urh-t)L"~IIICI1 ge!lcl utztes Blid

SO ippel for I he we b . xm 1 111 a I is 10 be p I a ced in th e WEB- IN E' d i rectory of th e web di reciorv will be I ike the code given in Listing 2.9.

Listing 2.9, web. xmi

Thi, JSP page is working as client code for this apphcation, Save thts Hie as index. j sp inside lhe 'web' module of the 'Carr' folder. Follow the directory structure of pervious applical,ion session and shown in Fig.EIB-2.S.

The t i on. xm.L file is similar to the nUe given in Listing 2.4 ihatls lnside the stateless

The only difference is here that we have the coruext-root name as 'Cart', li ke:

code files described in listing V; 10 listing 2.9 are the files that are required for au r sta Ie fu I appl i cauo n,

41

Craating aar fila

Now lt's time to create an • ear file through the command prompt similar to the one creajed ln case or stareless sesston bean. Here we have created an ear frle named 3S by using the command "j ar-C" f cart. ea. '. '.- You have to use this

sta )'ing at 'Ca rt' di rectory in the com man d prompt. And now d ep I oy you r

l.e. Cart.ear. Here we have used the weblogic server for the deployment. After deployment of "COH:t. ea.r", open the browser wlrh the corresponding address bar. As. used the weblogic, the browser address will be "htpp: Illoca Lnos c : 7 OOl/Ca 1: t', you will see the output as shown in Ihe Fig.EJB-2.21,

Shopping Cart

Adding Items to Shopping Cart

Enter [tem. Name: I, __ urncborrectnucn geschOtz!es BIId

Ail,n_,"'1

[J

F!g.tjll' z, n

This is the output what we have expected from the client "index.jsp", execution, there is no item at [he time of tnltlailzauon, and that ;is "Olhing., Here you can enter the name of an item of your choice 10

Enle' the item name in the text field' and click on • Add Item button", your

like as shown in Fig.EIS-2.22.

42

Urr~b rrechtl: 11 g sohiit.<1 "~\ .r rio

Clrapler 2: 5 ... ;0" 8"""

Fig,[]B.2.Z2

In this application, we are able to store the previous stale of application which is the main required criteria of sta lefu I session bean appllcatlon.

Choosing 8tJtw88n Statel8ss or Siateful S8ssion Bean

From the preceding dlscusslon, we found out that the Stateless s e sslon bean never stores any session Or the client related state information between the transactions. More than one user Can share the stateless session bean and hence the overhead of creating bean every time ;, reduced. The server use' the bean instance whenever il is needed and then ~gil'in puts it bad when the work is completed, Any instance of the session bean can work for any client. This is the reason for whlch the Stateless session beans provide a better and faster performance than the stateful session bean.

Comparatively the stateful session bean performs all the features opposite to the stateless session bean. t( maintains the 'late or the client related state informalion thai had taken place inside the transaction between the server and the chern. 50 now, .fler learning about .11 (he fundament. Is ,regarding these two types of session bean, the quesuon may arise about which session bean the user shou Id use, whether he shou Id use the sta teless sess io n bea n or statefu I sesslo n bean. and where to use these types of session. Our next section covers the approach of decision making that is related to the two types of session bean,

Choosing of the stateless session bean

Stateless 51'S, i On be" n is a good cho i ce in Co se where your appli cati On need I not to ma i ntai n a stale for a particular client, If your appl rcauon is not performing any bean-to-bean implementation for storing of the state information, then it is a good practice to make the use of stateless session bean inside that. We have already given an example in this chapter regarding to the stateless bean configuration. Let us lake another example, suppose you are developing an internet application that allows the visitor to dick on a I ink that is written "Contact us' and after clicking that link, it will send an email 10 the corresponding address that is inside the "contact us" link. So here, in this example there is no need 10 maintain any state. II you want to develop this application by m:ing stat .. ful session bean, then it is like the unnecessary things that you are performing and this would in turn consume the "'emory space. Here, the on Iy work that we are

43

EJB ,,10 i" Simpl' Sl'p~

perfarming is to send an ,,-mail to the correspondtng address, so, here is no such requirement of rnalnrnlning a stale, by which your applicatiorl will become more complex. So in this type of application, user lakes the consideration of lmplementing the stateless session bean rather than the s ratefu I sess ion bean.

Choosing of 5tateful session bean

When your application needs a sequence of operations that depends upon the result of the pervious operation. then you need to make the use of the stateful session be-ln. The main motto of the stateful session bean is 1.0 manage the state between the cllern and the server till the transaction between them i, over, Here each operation that is performed or done in a particular session. Here the session period is mainlained for a particular cllent only. No other clients can interact with this client by using it, session. So in tho interaction, individual client is having their own sessions. When user want> to develop application like onl lne website of any company, the developer need to maintain state, so it requires the lise of the stateful session bean. The company we~ile olfers his employee 10 view his personal information, 10 edit or update his profile" like ,0 many operations. Let us see what the application does:

I:l II accept' the login information provided by the employee.

I:l It calls an EJB to perform the validations of the login data whether il is correct Of not. a II sends confirmation oi author.xauon to the user or employee.

I:l It culls a bean that accesses the profile information for the authorized or valid user. Q II performs SOme work relaung 10 the employees requirement,

.AII the preceding works are performed for ~ single cllent within a single session, Other employees are not eligihle 10 access this pankular employee's account, Ihis ls in fact the main feature of J staieful session bean,

By now you must have understood what the exact working of stateful 'session bean is. All the prece(ling tuncnnns can not be performed by Ihe stateless session bean, asthls does not store the 'SWe of the previous actlon which would be required for the next action.

It can be said that the user can usc the slalef,,1 session bean, if any of the following conditions ore satisfled:

'Q The bean state must be in;tialized when it is created,

I:l The bean need. 10 hold information about the client across method tnvocarlons, I:l The chent is an interactive application,

Summary

In this chapter. we hove completed full introduction with the one of the most important type of EJB l.e. Session Bean. The two different subtypes of Session Bean i.e, stateless and stateful have also been discussw with all their use cases and lmplementauon detatls, The development of different components for on applicauon us['ng Session bean and the deployment of such application have been fuily described with sample examples,

In next chapter describes another Iype of EJB l.e, "Me,sage Driven Bean" with it' need, features and illil implementation through running ex.)mples.

44

U rheberrec htl lch ge5c h (jutes Iv! ateri"

Urhebsrrechtllctl ge5[:;:llutztes r. ... fal[Jri[Jl

£/ B 3.0 in~ Simple S rep'

The term Message Driven Bean (M,?B) itself suggests Ih~tit is associated with some sort of messagmg. Messagmg Can be defined as ~ method ot commumcatron between software components or appl "a lions, which is essential when we are wlklng about some enterprise level appllcauons. A messaging system is a peer to peer f"dlity in which a messaging client can send messages to other c llents 0" well as receive messages from other clients .. Here each client connects to a message agent that facilitates the creating, ,ending, receiving. and reading of messages.

Java Messaging Server OMS) is a core service provided by 12 EE application servers. JMS allows asynchronous invocation of different 'services via messages, The iMS clients send messages to server maintained message queues. To monitor message queues, we need a special kind of EJB, " called Message Driven Bean,

In order to know all about Message Driven Bean,. yOU' need to 'know about '~'MesS<lging Concept"

and IMS first. ~

Messaging Concept

When a message is to be transferred from one component (0 anomer, a common desunauon is used In collect the message loeing transferred, The sender sends the message io this destination and the recipient retrieves message from this destination. In this process, you will find that the sender and (he' receiver need not be active at the same time in order to communicate with each other and this Can be implemented asynchronously. In fact, it is not necessary for the sender to know about. (he receiver and also for the receiver to know about tile sender. The only thing that I.he sender as well a, the r",eiver must know is "which message io'm31. and which destlnatlon wi II be used in order to com rnu n i catc".

A messaging concept is defined as an asynchronous cornmunlcatlon between system components. 'In order to understand I.he rnessaglng concept, let's take a real world example that is related to Our daily life. Suppose you want to convey some message to your friend; the easiest way is that you simply call and talk to your friend over the phone. But what will happen il your friend is not there on the other side. In such a case, you will opt out (or the voicemail message process. Y ou S imp Iy I eave a vo i cema i I mesS-'g,e for you r frie nd in order to co nvev your message to him. On the other hand, your friend will get the message later on when he accesses, it. Here. the votcemail message service makes the communication asynchronous by 'toring your message so that the receiver (your friend) could receivei! later. So, here the volcemall service performs as a "'iddlem;)n between the messoge sender and the receiver so that they do not have to be available simultaneously, The MOM (Me,sage·Oriented Middlewa'e) in the messaging concept performs tile sirn] lar working to that of the voiccmail m"""ge service in the above example. The Message.Oriemed Middleware 'is a type of software that enables asynchronous messages between the system components, Just like the volcemall servlce, the message-oriented. middleware enables asvnchronous messaging between the sender and the receiver so that they do not have to be avail a b Ie s;,n u It,) neo LJS Iy. Wh en J. mes>agc is sent, the softwa re stores the message in the location specified by me sender and acknowledges the receipt of the same 'mmedi"tely. Here the sender who sends the message is known a, the 'procucer' and the location where the message is stored is known as 'destinancn", Fig.F.JB-3.1 shows the working of a message oriented middleware in detail.

46

U rheberrcc htl lch gesc h utztes Iv! ateri a

Consumer

FIg.EJB.3.1

The software component that receives the me.sage. Is coiled the me""!;,, consumer. So, from fig.EJB-J.l, it is clear that the consumer (an relrieve the messages "nylim" from Ihe stored area.

JMS

Java Message Service, shortly known as 'JMS' is In application programming interface (API) for accessing enterprise mossagtng systems. This java mess~ging service make, it easy to wrile business appllcauons Ihat asynchronouslv send and receive critical busirless data arid events Ihal are inside the Enterprise javalleans IE)BI. )MS facilitates sending messages from enterprise bean using a messaging service, known as messJge broke, OJ router. This jMS is [ava H ,'PI that supports the formal communication known as mess"ging between computers in the network. There are man)' types of messages available inside JMS. which are as follow>:

IJ Ted Message: It contains string.

IJ Map Message: It contains name/value pairs. Each name is indicated as a string object and

each val ue is a java pri mi rive type.

IJ Byte Message: It contains a stream of uninterrupted byte.

IJ Stream Message: It contains a stream of java primitive values .

.-\11 these messages are represented by interface. Inat are derived from the javJx.jms.Me55ilge interface. The javax.Ims.Message interface defines message header and the acknowledge method for ali messages . .A JMS mes,age is composed of Ihe (ollowing three parts:

IJ Header: Header fields contain SOme values that are 10 be used by both the clients and the provide rs to identify and route me.sages. All mess"ses support the same set of header fields. Generallv, it is composed of d<:ltvery information and rl,et-;tdaIJ.

IJ Properti~s: Every m""ose contains buill-in facility for supporting applicatlon-defincd property values. These properties provide an efficient me-chanism tor supporting application defined mc-s,age filtering.

47

U rheberrec htl lch gesc h utztes Iv! ate,i"

fiB 3.0 i" Simple 51eps

o Body: A JMS API defines several types of message body. These message body styles cover"

majority of the most commonly used messaging styles.

To send a message, you have to firs~ create a message object by calling one of the create message methods of the session interface. You can use any of the following methods, of jMS session interface. A JMS session is J single-threaded context for producing and consuming mt",sages.

c create TextMessage() I:l cre;lteMapMes<age() I:l create ByteMessage()

I:l createstreamwessager) a creatcObjectMes:;ageO

To send a JMS message, we need a connection with the JMS provider and also a destination address for the message. It is Ihe work of the JMS connection factory to make il possible. Cormection facrory makes a connection to the provider and the destination address is .identified by a, Topic object. We can achieve both the properties of connection factory and the Topic object by injecting @java>: _ annct.at.I on. Re source directly. This connection fac~ory is equivalent to the DataSource in )00e. Tile Connect i.on se ct.o r y provides a ,1MS connectlon 10 the message router, Topic is a network-Independent destination to which rile message is addressed. In JMS, messages are sent through either Topic or Queue. for more le'l on Topic and Queue, see the 'Messaging Model' section of this chapter.

Now, let's take a look at the messaging models available in the java message service.

Massaging MDdal

There are two Iypes of messaging models available inside the messaging concept such as: o Point-to-point messaging

I:l Publtsh-Subscrlbe mes~aging

Pbm~~mtm9~gi~

As the name suggests, this type of messaging is performed between one producer and one consumer. A single message travels from J single producer to J. single consumer. Hero the place, where the message is stored is known as 'queue' butit does not mean that the messages will be retrieved in a particular order. It means that if there is more than one receiver for a mess..lge, a single receiver is chosen randomly at a time. The classlc diagram of a polnt-to-pclnt mes>aging model is as given in Fig.EJB-3.2. The pcirn-to-polnt messaging model allows JMS cl ients to send and receive messages both synchronously and asynchronously through the 'Queue'.

48

U rheberrcc htl lch gesc h (jutes M aleri a

Publish $ubscn1NJ MessJ#ging Modo!

This model is a little different from the point-to-pclru me'5aging model. It' functionality is like "posting a me5Sage to an lnternet newsgroup" Here in thiS CJS<C, a single producer generates a message wh ich can be retrieved by an), number of consumers that are connected 10 the destination. Here the destination is known a, "Topic" and tile consumer is known as the "subscriber". The classic diagram 01 the publish-subscribe messaging model as wcll as it, working criteria can be well understood by looking at Fig.EIB.3.3.

In fig.EJS·] .3, it is clearly shown that there are three consumers Or subscribers who are able to retrieve a DOpy of the message from a topic at the same time. The rate of sending the messages by the producer is not dependant upon the rare or lhe receiving capacuv by Ihe consumer. JMS clients that USe publish-subscribe messaging model can establish durable subscriptions allowing the consumers to disconnect and later to reconnect and collect message, that were published while they were not connected. This type of messaging model is essential when you have 10

49

U rheberrcc htl lch gesc h (jutes M ateri"

broadcast the me5$<lge, across a number of systems. Sending a single me>sage to all of your friends present in your triend-Hst is one such example of publish-subscribe rnessaglog model.

fiB 3.0 III Simpl" S'Icps

What is MDB?

By now, you must have got some ideas regarding the messaging concept and JMS. Now, let's learn about MOB IM~sage Driven Bean), Me;sage Driven Bean (MDB) can be defined as a special enterprise java been component that can receive JMS messages as well as other types of message services. This bean allows the j2ee application to process messages asynchronously. It acts as J JMS listener which is similar to that of the event listener; the only difference being that it receives messages instead of events, The message may be sent by any j2ee component that may be an application client or another enterprise bean or web component or by any JMS appl i cation.

Unlike the session bean. message driven bean cannot be accessed by any client through a business interf"ce. After all, a client is not able to identify a message-drlven bean and consequently it cannot interact directly with the MOB. The only way in which a client can interact with a mc"Ssage driven bean is through the messaging system. You will have to provide message provlder-spectllc API .. like JMS to send themessage from the client and on the other 'ide this will be received by the message-driven bean. In this version of EJB, you will not find any change related to the concept of messag" driven bean of the previous version. It only simplifies the configuration u,ing the concept of annotation for our easy achievement.

Why to USB MOB?

There are a few reason, why EJB developer, are more indined towards uslng the message-driven bean. These arc described in the following points:

Multithruding

Generally, your business application may require multithreaded message consumers that can process many messages concurrently. You will not find any complexity while processing a. they are able to h a ndle multithreading without any additional code. They manage the incoming messages by distributing them among the multiple instances of bean that are present inside the pool. When a new message reaches the destination, an MOB instance ls retrieved from the pool to handle that message. -

SimpliliBd MIISSJlgittg Cot/II

Message-driven bean gives a relief to the EJB developer from coding the mechanical aspect of processing mess..gcs. such as looking up connection factories or destinations, creating connection. opening sessions, creating consumers, and attaching listeners,

St8rtiog MfI$S8gl1 Cansumption

Message consumption starts when a user starts picking up messages. from the queue. Starting message consu mptio n tb rough a user dr ive n rna nua I process is not oesi rable, On the server si de, the execution of methods on the server startup is highly system dependant. The same case is also raised while stopping message receipt. On the other side, registered MOBs would be

bootstrapped by the container when we start or stop the server, ~

50

U rheberrec htl lch ge5c h utztes M ateri a

Charactaris1ics of Massaga drivan boan

The following points are some of the characteristics, which are implemented by the message driven bean:

'IJ A message driven bean does not have a remote or local business interface.

IJ You cannot call a message driven bean by using an object-orierued remote method invocation interlace, The message driven bean processes messages that can come from any messaging client

o M e,sage- dli ven bea ns suppo rt generic Ii sten er mel hod, for messa ge de I i very, 'IJ Generally, message-driven bean listener methods do not have return values,

EJB specification doe, not restrict a message driven bean listener method irom returning a value to the client; but still, certain me;saging type might not be suitable for this. For example, let's consider a case of the listener interface of J messaging type, which supports asynchronous me,,;aging like JMS. In this case, the message producers do not wait lor your message driven bean to respond as the interaction between the message producers and consumers is asynchronous.

o Message-driven beans might not send excepuons back to cltents

E,JB does not restrict message driven bean listener interface method. from throwing application exccpnons but sHII, some of the mes.<;'Jging lypes might nOI be able 10 throw these exception. to the clients. In case of that listener interface of messaging type which supports asynchronous messaging like jMS, the message producer would not wait for the MOB to send the response, This is because 01 the asynchronous nature of the mteracuon (or which the client cannot receive any exceptions.

o Messdg".driven beans arc stateless in nat ure,

Similar to the stateless session bean, message driven bean do not hold any conversational state for a specific diem. They do not have any client-vlslble identity. In this case, the container can similarly treat each message driven instance as ,111 equivalent to other instances. Thus, m u ltiple instances of the bean can process multiple messages hom a ,IMS destination. This is why, it is stateless in nature.

D Message-driven beans are si ngl e threaded,

A single message-dnven bean can process only one message at a time. The coruajner is responsible for serializing messages to a single message-dnven bean. so there is no need for s}'nchronizing code in the bean class.

Structure of an MOB

The structure of MOB can be summarized thrcogh the following statement"

o No home interface is required for MOB.

o Remote interface is also n01 required for MOB.

o The bean class is the main focuslng part of the Message Driven Bean.

The message driven bean I, very much similar to the ,tateless session bean, The interaction between the MOB and the cllenl is Similar to the way it interacts with the IMS applicauon or JMS

51

U rhcberrec htlich gcsc h (jutes M ateri <1

1.0 in

server. All instances of a particular MDB type are equivalent as they are not directly visible 10 cl lent and mal nta in no conversat i ona I state.

lifB cycle of Message DrivBn Bean

The I ife cycle of message d ri ven bean i, exh ibi ted th rou gh two sta tes, such as: a Does-n ot -exist sta te

a Method·ready pool state

The message driven bean is either in the does-not-exist state or in the pooled state. container decides to insert a new instance 10 its pool, it creates a new instance and required dependency lnjectlon, II performs all this by calling set.Message[)< i

and ej berea t.e (I methods.

The setMessageDrivenContextO provide, an access to the runtime message-driven the container provides for a message-driven enterprise bean instance. It is called by the after creating the bean instance and it passes a reference to " Mes$ageDrivenContext the bean. This mean, I,hat the container passes the Me,,"seDrivenConte><t to an

the lnstance has been created. A message-driven bean can also acquire a MessageOrivenContex.t U5ing dependency injection by 'imply providing ihe annotation. Tho message-driven CQnte::II:1 remains associated with the

long as the instance is alive, that is throughout its llfetlrne, After the instance creation Mr:.>5ageDrivenContext, message-driven bean is ready to receive messages. tf any @postConS1Oruct has been used to define a hfe-cvcle call back method, then invoked here. According to the configuration, the application server will generate an

of beans at the start up time. The size of this pool con be expanded as the size of

in creases, When til e bea n i. nsta nee is process i ng a JMS message, i IS a nMe s ,sg ae I) Is perform the work. The container can destroy an instance by removing it from the pool at system shut-down time. This can also be done when the container wants 1.0 decrease the the pool to conserve memory or to make the best utilization of the memory. ln this case, it

to call the e j bRemove() method, before (he instance ls ready for the garbage collection.

tf the container decides to take an. instance out of the bean pool, it calls the OP

method. The diagr~"mmJ,licJI representaticn of the life cyete of the mes,age driven

siven in fiS.EJB-3,.4.

52

U rheberrcc htl lch gesc h utztes Iv! ateri a

CI ••• _ncwlnstanCOI) Dependency !njection @P05lC<Jn5IruCl

onMessage()

Fig.E/B_3.(

You can observe (hal, (he l.ife qcle of the sta(eles, se,sion bean, which is de.sCtlbed in Chapter 2 ls quite srmilar to that of (he message driven bean in thls chapter. Let', now discuss the two

states of the message driven bean, .

Ooes-Not·Eltist State

When a message driven bean instance is in the does-not-exist state, it ts nOI considered as an ; nsta nee in the memo ry of the system. tt mea ns that it has not been ; nsta ntlatcd yet.

Method·Relldv Pool Stllte

The message driven bean instance enters into the method-ready pool state, when the container needs it, As soon J' the EJB server starts, It may creme ~ number of instance, and enters them into the method ready pool. I{ the "limber of MDB instances are tnsuffloent {or I,andling the

incoming messages, more instances can be created and inserted 'into the pool. -

Transitioning to tho Method-RoadV Pool

When an instance move, from the Does-not-Exist state to the Method-ready pool, three operation, ore performed on it

IJ FirS1, the bean instance is instantiated when the container invokes the newj n stance (I method on the MDIl class,

53

U rheberrcc htl lch gesc h utztes M ateri a

fIB 3.D i" Simple 51q'"

a Second, the contalner injects the required resources, It injects the resources with the help of

a nnotat i on 0 r XM L deploym ent descrl ptor.

a Third. the pos t con s t ruct; callback is invoked by the contalner, if it is present.

The bea n d a ss mol' or may n ot h ave a method tha Ii, a n notated wi Ih @javax. e j b , Pas teons t ruct.. But in case it is present, this annotated method will be called by the container only after the bean is lnstantiated. The @PO$tConstruct annotated mel hod ca n be of • ny n a me" but compu lsoril y it wi II ret u rn vo ida nd t he method IV i II be made up IV i th no pa ram eter.

While using the @PostCons:ruet annotation, your snippet will look like the followi ng:

Lifa of M D B in tho Motho d.RII.ady Pool

As soon as an instance reaches to the Method·,eady pool. it is ready to handle lncomlng me"age,. While a message is being forwarded 10 a MOB. it is delegated 10 any available instance in the method-ready pool. While an instance is executing a request, it is unable to execute Of process other messages. The MOB Can handle many messages by delegating the responsibility 01 handling each message to a different MOB instance. Whi Ie processing, once the instance has finished its work, it is immediately available to handle another new message that is present i ns i de the message-d ri ven bean.

Doath 01 thll MDB InstanclI

When the server doe> not need a bean instance, its state is changed from the mejhod-ready state to does-not-exist state, This type of situatlon generally OCCurs when the server decide, to decrease the total slze of (he method-ready pool by releasing one or more instances from memory. But before this, the container invokes another callback method annotated with @' ~~eDest roy on the bean tnstance, At this time, the bean instance can perform any cleanup ope-anon like 'dosing open resources' using this @PreDestroy annotation. The Important point to be remembered bere is that @?reDestroy callback method is invoked only Once in the lile ~ycl~ of MOB instance. Your snippet will look like as follows:

Writing an MDB

Before going to write a message·driven bean, a developer snould take the following tasks into consideratlon.

a Implementation of the j eva". ej b. MessageDr i venBean and

j avax . j ms , Mes s aqe l.Ls t erte r interlace inside the message-driven bean class,

54

o.ap I", J: M""""g" Drit'£J' /JeQ'.I

c lrnplernentatlon of tbe business. logic inside the on)4es s~ge I) method. Now, lei's Iry 10 understand the above points One by One.

of MessageD riven Bean and MessageListener

bea n, are clJSSCS that imp lem ern two tntertaces sue h as jms ~ Message:Li 5 t.ene r and j ave x . e j b. MessageDr I vengean. The 'second one is In case 01 the previous versions of the EJ B, it was compulsory to use the me>sage driven bean, but this is not required ·in the new version 01 the EJ B, that is EJB3.0. Along with this, every message-driven bean implementation class must provide a 'no-arg' constructor.

of business logic inside the onMessgaeU

o nMe S 5 age () method is the 0 n Iy meth ad that is lou nd i ns i de the JMS message listener java". jms. MessageList-ener. This accepts JMS messages which can represent such as a byte message, object message, text message, and map message. The main onMe s sage () method is to type-ca st the i ncom i ng message 01 a ny type 10 a text message and to display the text. It acts something like a business interface as all the business exhibited' inside the onMessage I) method of this message-driven bean.

we a re Usi ng a cal cu la tor rei a ted app I i ca tio nand th e ob j ect ive olth i 5 si mple a ppl icat ion is calculate the investment. While the server is calculating your investment, it will give a 'Please wait while I am checking whether the mes",se has arrived', to let the user know he has to wait for therequlred result and only after sometime will he get the correspond: ng For preparing this application, you need 10 create following code files:

Calculationkecord.java RecordMa n ager, i a va

u Co leu I ator Bea n.j a va calculator.jsp

a check.jsp

a index.htrnl

Calculanonsecorc class has been, described in Listing 3.1. This class has Calculationkecord Timestamp, double) constructor, which sets three different fields-.sent processed,

Calculationkecord.java

55

Tile RecmdManager cia" provides different methods" such as addRecerd (J , getRecerd (I . The cod e for the RecordManaser class has been provided in Listing 3,2.

Li sti og 3.2; 'RecordMa nager. ja"J

The Calculatorssan class ls our Mess"Be Driven Bean class. This cia" has been annotated with l&i'MessageDriven annotation which makes it sure tim the container sees it as a message driven bean. See the code of Ca lc ul ale r Sea n class in l.isl j n g 3.3.

56

Listing 3.3, CalculalorBe.an.java

Urh berr II i h g sc;,ulli Bild

57

3.0 rrr

Here, we create a bean which irnplerrents javax.jrrs.rvtessagettsrener interface and we this program using @MessageDriven annotation 10 specify EIB 3.0 cbarectenstics, as Listing 3.3.

Compile ce Lcu'l a t Lonaecor-d . j oval RecordM.a.nage r , java,

CalculatorBean. j ava files and get the class files in a package named as '[rns', thai :i n side you r e j b mods Ie. Here we have given a on a me of (he bean m odu Ie as directorial structure of the fifes of thls MDB appllcatlon is similar to that of the excep t Lhat here we ha ve used ou r bean mod u leal 'bea ns', whereas incase of

have used it a, EJB.

The ca Lcu Lat;o r , j sp and check. j sp Jiles are the required )SP files Jor this we are pe rform i ng the feq u i red connectl 0 n wi I h the 'Queue' usi ng til e lookup in Listing 3.4 for calculator.jsp,

listing 3.4: calculator.jsp

UrhBbernx;~1 II" h g eschulztus B Id

58

The snippet for check. j s p ts given in Lisling 3.5. Listing 3.5: check.jsp

59

3.0hl

The welcome file that we have used here is i.ndex . html. The snippet of the ~·eb. xml in Listing 3.6. U,ling3.6:. lndex.htrnl

Uri] bo>rr .. hllioll gas l'ulLles B I I

The ca leu La t cr . j sO', check. j sO', and i ndex . ntml Ii les are saved inside module in the same way a, done in session bean application.

After the completion of program, you might be thinking that why we are

h.", e , whi Ie we cou Id have ach leved I he same resu II usl ng sess i on be. n. concept of messag i n g wh ;en i, essent i a I lor d i IT erent busi ness tas ks an d be in g u5ing MOB. These busin ... ss tasks are complex and would have required the use 01 wh i eh to kes a long time 10 complete. On th e other hand, i r you 3 re us i ns the

60

3: DriW,j Be..'fm

execute certain task" these tasks would have to wait until the sesslon bean ls completed and retu rn rhe control to the app lieati on,

EJB

this sample appficarion on the appl ication server- Weblogic 10, we have to some steps, The.;e step' are being described here and mU51 be carried out in the foliowinB order,

tho ear file

completion of ~II the coding part. now is the t,ime to gencrote an .ear me for the proces, in Weblogic server. See Fig.EIB<~"S for the command being executed for an .ear tile of the appl icaticn,

U oeberrecht Ich g ascbutz Ins B ta

flg,F.JU·l.;

thls ear file through t,ne command prompt using the command j a" -cvf MDB. ea r changing your current directory to MOB (here our' rnai n project folder is MOB) "0 that of beans module. web module, and MHA·tNF will be found in the MORea, file. flrstline in Fig.EJ B·3.5 lor the executed comrnand.)

JMS sarver

need aIMS serverin order to runthis appl lcarlon and the steps 10 create ;) JMS Server are a,

1. Open [he Web logic console using proper uri, '"y ht!p:l!localhosl: 700 I /ccnsole.

2. Click the option services of Domain Structure [rom the lelt panel, as shown in Fig.EJ B·3.6.

3. Click th e expa nsi 0 n b uno n( +) b esi des Mess~ gi "g op: ion 10 expo nd it. as ,11 own in Fig.EJ 8·3.6.

Click the JMS Server oplion to see the infomtation regarding tile creation of 1M, server, ,vnicn has also been shown in Fig.EJB.] ,6.

61

EIB 3.0 in Simple 51,p'

U rnebarrec hllch goo c hO tztes Bild

Fis-EIB-3.6

5. Click rhe Lock & Edil buuon 10 acuvaie New bunon (Fig.EJB-3_6l_

6. Click the New button 10 create a new JMS server (Fig.EJB-3.6J.

7. Emer the name of your )MS Server, say )MSServer, in Name field.

B. C/ic k the C reate aNew Store b utton to create a new persistent store for yo ur )MS server, as shown in Fig_tJS·3. 7_

U,llooorrochll en qaschutztes Bid

62

(1'"pJor 3: M'~"'g< Driv,,, I)e.]"

9. Select the type of your persistent store. We have selected File Store as the type here as shown in Fig.EJB-3.B and click the Next button 10 proceed.

UrholJe,,"chll en geschutTe, S,id

F;g.E)B.J.8

10. Configure your ~ew persistent store as shown in Fig.cIB-3.9 with :its name, say FileSlore and the target server, say Admin5ervet.

11. Clkk the Fi n ish bu non to co mplete th e creatio n 01 new store lor yo trr 1M S Se rver.

U rhebe r",,1l11 o h geschulZles B,ld

FIg. E) J!..3.9

63

U rheber reo h III h g sc h utztes Ma!er; a

12. Now, 5elect the new created fi leStore persistent store for your JMS Server just created with name r i leStore and click the Next button, as shown in Fig. EJB·3.1 o.

Url":ebarreclllllci 9 scnurzres 8,0

PiS·E/l<-l.W

13. Selec113rgel server instance lor your jMS Serveras shown in Fig.,EjB-3.11 and dick on Finish button.

Urhat)6rr .. ~llrl ch U sch J!>.] :; Blki

64

14. Click the Activate Changes button, as shown in Fig.EJB·3 .12 to activate all the changes made t.ill now.

Ur 1"~'" II i~11 g. ch(jI~1 Bild

Fig.EJB-.l.U

Step3-Creating JMS Module

1. Open the option JMS Modules from the Dornatn Structore by selec(ing JMS Modules option a, shown in Fig EJB-3.13.

2. Click the Lock & Edit button ln left pane to enable buttons in the right hand pane.

3. Click the New button 10 create 3 new JMS module. as show" in Fig,EJB-3. r 3.

U,hebefTechl ich ~EtSGhLJlz.les Blld

65

Urheberrechilich gesotrulzles Ma "''''

EIB 3.0 jn Simpl. Slep'

4. Enter SOme name for your IMS System Module, '~y Sy.temModule and dick on Next button 10 proceed, as shown in Fig.EJB-3 .14.

UrhBoorrachtl en Qoschut:ms BMl

F;g.EfB.J.'4

S. Check the optionprovided 10 ,eiecilarg.el server which has been shown in Fig.EJB·3.]5.

U rh ehi,; me nu C 11 gesc nutztes B ild

F;g.El~l.,l;

66

6. Click the Ne.! Bullon below the Targets in Fig, 0113-3.15 10 proceed further in the wizard and to open the Fig.EJB-J,16,

Urh ,bnr hll~ h g"S hL IZ les B ld

fig,UII.J.16

'7. Now, check the option Would you like 10 add resources 10 this JMS system module (refer

Fig.EJB-J, 16) for adding the resources,

B. Click the Finish buttontreter Fig.E)B·3.16)to accept the settings.

Now you will find the option to generate resources under our just created IMS moduleSystcmModule.

9. Click New button in Fig,EJB-3.17 to create resource and proceed next.

U rneberrecru ien gas c h urztas Bi 10

67

Urr~b rrechtll 11 g sr,hiHll "~\ r rial

EIIJ 3_D in Simpl' $I<p'

Here you will find several options for creating resources. Depending on the type of resource you se I ect, you are pro m p led to enter some ba s i ci n format i on for ere<! Ii ng III e reSOU rces, Ou r appllcation needs 10 configure the "Con nectl on Fac lOry"' and "Queue" resources. So we will add both of these One by one.

10. Sa/eel the radio button for Connectron F~ctory and click the Ned button, as shown in fig.EIB-3_'t8

___ ri'_~ I __ -t......,"_'r..! ~- .. - .... , :

~ ..... I .. ~1M· ... ~ ... I ......... r :I.o .......... _ ... •

._- ... -. '--"'~'."""~-'--.-- -- _ .

r-.n;."' .. _ ... ._,... ... _" ...,._ ,_.__.<:r.......;: ..

,_'" ..,. _ _..... __ ~., _ .... o..-:.. ~ .. ~_ ...,;""""v.._ .. ...t

qq""""".-..qnliHlo'"" __ "'"....,_·,_...t.u __ I:r~_

:-~ML ... .=..-:=. __ ~..::'==---·., ..... .,~

. ~ , .. ~ .....

• t. _

........... -....... -

. ~ .. ~~ .....

~~~ ...... '"i"{o

• .,....~~~~--'I::"T

_~ ...... _'~~ ._,.;r'_,.;.--..<"O."<" ••

__ .. ~ .... OO'OQIr1 ··_ ........... • ...

flg.EJEbl.18

11_ Emer Nome and INDt Name for the ConnE'ctionF.actory resource being created, a" shown in FiS.EJB-3.19. Remember L11at you have to provide the same name as well as same' JNDI na me th.1 you have provl ded in 1 he cl ient fi le,

12. Click the Finish button 10 fin ish the configuration ISee Fig.E)B.3, 19.

U rh eberrecmhc h gascMu!Z'DS B Id

rig.EJIl--J·19

6B

13, Again, click the New button to create another resource inside this JMS Module, as shown in Fig_EIS-J,20_

U,neborrecht i~h geschutzles Bild

fis-£Ja,n~

14. Select the option "Queue" and click the Next burton, as shown in Fig.EIB-3_21_

U'h~bermchl-,ch gas c nutztes Blld

Fig,E)B.J.ll

69

U r ho berrec \111 ie h ~""ch iitz I 5 ~ 1~"Qri"

fiB ),0 in S,impl' SI,W'

15. Provide a name for the queue as well as a IN DI nome similar 10 the name that you have provided in your dien! file and click the Ned button 10 proceed, as shown in Fig_~JB-3_22_

U rho berrcc h II c h g~sc h utztes B, d

FIg.E/B.l.22

16. Click the ·Create a New Suhdeploymeni" button to create new Subdeployrnent, as shown in FiS_EjB-3,23.

Uric bnrr cc h 'lid, gCSclHlIl tes B il<:l

70

1 7. Emer the na me r or I h is su bdepl oym ern, sa y test Que u e a. n d c!ie k the OK bulla n, as 5 hown in Fig.EjB-3.24.

urhebe recnucn gQschutztes BI d

Fls£jB·l.2l

18. Sele<;llhe newly created subdeployrnern, soy tesrooeue (Fig.E)6·].25).

19. Select the largellMS server that you want to use as targets. say )MSServer (Fig.EIB-J .25).

20. Click fin;jh bunon 10' finish the generation o( this resource. as shown in Fig.E)B·J.25.

Urnooorrm:hll.ch geschutztes 81 d

71

Urheberrechlllcn gesolrutztes Ma "''''

£/B 3.0 in Simpl. SIep>

21'. "'nally, click the Artjv~l.e Changes buuon to activate all the changes mode as shown in Fig.fJB-3.26.

UrI,,,,,,,,,,,,,htl ch fI~sch[llZt~' Bild

F;g.~l!'-l.26

jn the slrnilar way, you C;Jn create other resources a:s. per the requirement of your ellen; class.

Step4-Depl Dyi n 9 EAR file.

After creation of jMS server and jMS modules, go for the deployment process of the EAR file.

1. Click the

8-3.27.

UrIlEb~tr"'lt i 119e,;ol\ulZt s Bild

fig.E] e:-J.l7

72

U rl eborrec h II lc h Jes" h [,Ides M il'~ri~

2. Now click the Ins(all button to start your deployment which has been shown in Fig.EJS·3.28.

Urheberrecht ieh goschlllztes Bid

Fig.E/S.3.28

3, Select your corresponding ear file by browslng the location "'0'0111051" and deploy your corresponding ear lile by clicking On Next {see Fig,EJB·3.291 buuon 10 proceed.

Uti eberlecl1lli!_l1 9 scmnztos Slid

.t'lC·t:.JtJ·;,,;.;::~

4, Click the Activa.te: Changes (sell Fig.EJS·3.30) buucn to activate all the changes.

73

EJB 3.0 iu Simpl" Steps

U, h "00' €!Cnll en U"5chulz lss B I -t

F;,~,~fIJ·JJO

5. Hnally, you CO" see your application deployed which has been shown in fig. ~IB·3.31. Now. you can run your application in the web Browser,

Urh "b""ec~1 ien gaschulzles Bid

74

Running the Application

Alter successful deployment of the ~1D3 _ e~ r file, follow the given steps to run you applicetion:

1. Open browser with the address htlptllo,allH)lt:7Q01/MOB to lee the welcome file, as shown in the Fig. E.IB-3.32.

0 .... · C' @ ~ ~'...o-", W·_·n 0:0' il - De.:t1

.i>oohM··;M·;;~,(~Pi:M'~OO]~ -- -tfO~ .... v.k>"K-" ~.~.:.~.~ .. ~.

l\lESSAGE DRIVEN BEANS

F1g.E/!J.J.5Z

This is the index.html known as welcome file oi our message driven bean apphcation. Now you can dick the burton "Message Driven Calculator" to lee the output of calculator.jsp poge which has been shown in Fig. EJ B-3.3 3.

fiS·E/S-J.33

75

U rheberrec htl lch gesc h (jutes /vi ale,i a

U rhcberrec htl lch gesc h (jules M ateri"t

Chapter J: ~1\1 f551js_r:: Dr!i'Cn Bi'.rm

The text displayed on ctreck . jsp includes the time when mess"!:" was sent and when it was processed. In addition. it is also displaying the calculated result ".ing input values entered by the user through ca 1 cui a tor. j "Po

Summary

This chapter Introduced a different type of EJB which is implemented with the concept 0; asynchronous messaging between 11'1'0 different components. The chapter disCU5Se{J abOlJt )MS, Me.ssaging concept with different use case where Message Driven Beans arc used, The creation of different components in the creation of appl ication using Mc"age Driven Bean has been fully described through the example created in the chapter.

77

U rheberrec htl lch gesc h (jutes M ate,i"

Urhebsrrechtllctl ge5[:;:llutztes r. ... fal[Jri[Jl

£183.0 in Simple SIep5

Introduction

A transaction is a group of operations that must be performed as a unit. These operations can be synchronous or asynchronous, and can involve persisting data objects, sendlng mail, validating credit cards, and many other events. A classic example is a banking transfer, in which one operation debits funds from one account (i.e., updates a record in a database table), and another operation credits the same funds to another account (updates another row in that same, or a difierent. database table). The whole process can be taken as two different operations i.e. updating one account for the amount being debited and updating another record for the same amount being credited. This process of money transfer can not be considered complete if any of these two operations fails. There must never be a time when the amount to be transferred can be seen in both accounts. Nor can a moment exist when the fund can be seen in neither account, Such processes, which can be seen as group of operations that must be performed together as a unit, are known as Transactions.

The operations in a transaction are performed sequentially Or Simultaneously. After they are all performed successfully. the transaction is considered complete and committed. If any of the operation here fails due to some error or invalid condition .. the transactions are considered incomplete and all changed done by different operations of this transaction are rolled back i.e. undone.

One of the principal benefits of using EJB is its support for eoterprlse-wide services like transaction management. In this chapter, we will explore how EJB offers transaction services and how you can leverage them to meet your specific requirements.

Transaction·Where they are found?

In business, a transaction usually involves an exchange between two parties. For example when you purchase an icc cream cone, you arc exchaoglng money for food; similarly when you work for a company, you exchange skill and time for money (which you use to buy more ice cream). When you are involved in these exchanges, you monitor the desired outcome to ensure that you are not cheated, When you give the ice cream vendor a $20 bill; you are e.xpecting the ice cream in return as an exchange to the money offered by you. tn the similar manner, you want to make sure that your paycheck reflects all the hours that you had worked lor. By.moniloring these commercial exchanges, you are attempting to ensure the reliability of the transactions; you are making sure that each transaction meets everyone's expectations.

In business software, a transaction embodies the concept. of a commercial exchange, A business system transaction (transaction for short) is the execution of a unit-of-work that accesses one or more shared resources. usuall), databases. A unit-of-work is a set of activities that relate to each other and must be completed together. The reservation process is a unit-of-work made up 01 several activities: recording a reservation, debiting a credit card, and generating a ticket.

The object of a transaction is 10 execute" uoit-of-work that results in a reliable exchange. Here are s-ome types of business systems that employ transactions,

80

Urheberrechtllch qeschutztes ~tatcria

ArM

The ATM (Automatic Teller Machine). which is used to deposit, withdraw, and transfer funds. executes these units-of-work as transactlons. In an ATM withdrawal, for example, the ATM checks to make sure you don't overdr,lw; then it debits your account and spits out some money.

Onlinll Book StJJm

You might have purchased :many of your Java book, from an online bookseller, This type of purchase is also a unit-of-work that takes place as a transaction, In an ani inc book purchase, you have to submit your credit card number, it is validated. and then you are charged for the price of the book. Then an order to ship the book is sent to the bookseller's 'warehouse, This completes the online shopping of a book. These operations make a rransactlon to place order for a book.

Medical System

In a medical system" important and critical data of patient, is recorded everyday. this includes the information about clinical visits, medical procedures, prescriptions. and drug allergies, The doctor prescribes some drugs to the patient. Thi, prescription can be entered to some application which checks it for allergies, contraindtcations, and appropriate dosages, If "II tests pass, the drug' can b~ considered to be safe. otherwise not. These tasks make up a unit-of-work, A unit-ofwork. in a medical system may not be financial. but it is very lrnportant, For example f"ilore 10

identify a drug allergy ill a patient could be I;,tal. .

As you can see. transaction, are often complex and usually involve the manipulation of lots of dat •. At>y mistakes it> data can cost money, or even lives as dtscussed in case of identiiying the drug allergy. II is of utmost importance that transactions must preserve data inlegrity, which means the transaction must work perfectly every time or it should not be executed at all.

Why do we Need Transactions?

To find out the reason behind our need lor transactions. we will consider <) scensrio where an online reservation application is used to book a seat on a flight. There are several steps that have to be taken to process a rescrvatton;

CI An available seat on the flight must be located,

CI The seat is available and the process of reservation $1'''1\. Thi, requires gelling customer

information with detail, like credit card information, meal preference etc. - .

t:I Once the provided information is verified, the reservation is made lor the customer. Wi thou I. any proper concurrency control. it ls possible that the following would happen: t:I There are two diffe",nt customers trying to raserve a scat for their journey.

IJ Customer A observes that one seat is available and SlaJ15 entering his details to reserve the seat.

'IJ Simultaneously, another customer' B finds the "ery same sea! ava llable and begin, entering his details' from some other locotion.

IJ Suppose. customer B finishes first. So" hi' requ~'t is processed firsl and sear gets confirmed to customer B.

81

U rheberrec htl lch gesc h utztes Iv! ateri"

EJ B "J.Oi u Simpl'c Sleps

1:1 The customer A.I,o submits his request meanwhile.

Now. in this condition, if the second request sent by A has been allowed to update the same record, the lnlormatton of customer B would have been 10'1. In worst "aSG, the information of 001 h \11 e C(J stomers wou 1<1 have been I 05t.

You can e",ily imagine how important it is to prevent other situations such as number of processes Irying, to update the same sel of data in a database slmultaneously,

Transactional processing helps in such conditions. The concept of transaction has been supported by different method, for controlling the execution 01 aU the processes grouped together to make a tra nsa cnon,

There are' different scenarios where we need to create transacrions. One of them i-s when we need to group various steps together into J single unit of work This unit must either be completed successfully or not at all.

Transaction help' us in controlling simuhaneous access to the same set of data, Any client request to read or write data can be checked whether it is allowed to do sO Or not.

A larger fiB based system must be scalable enough and its diffe,ent components can he located on different servers. As, the system scales-up, the management and handling of simultaneous data requests gel difficult. The svstern should be eilsi I)' maintainable in case, it grows to provide new serv ices 1.0 rna re us ers,

Transaction Properties

Transactions can be simple or complex, small or large and can involve synchronous, and asynchronous operations, but Ihey "II have some core features in common, known as their ACtO L:Clmponent.s. ACID refers to the four chnmcterlstlcs that define a robust and reliable transaction: o Atomicity

1:1 Consistency
IJ tsolotion
1:1 Durability. Compliance with these four properties is requi ... sd for an entity 10 be considered" transaction, Because we need 10 be assured that thinBs will work as we expect them 10,

l.et's take a look at each oi the four ACID properties.

Atomicity

A transaction ls composed of one or more operations that are performed as a group" known as a "nit of work. The Atomicity property of transaction says tllat the transaction most always be, t reared as a si ng leur' i I s i m i I a r to atom, A tra nsacu on is a lways a set of d i frerenl processes a nd all these processes must finish successfully 10 make " transaction complete successfully. A transacuon fails if any of these processes fails. In other words. the only two posslblhties are there either all the processes of the transaction affect the svstem or none of them aflee!, the system at all

We can take an example of a bank application transaction where a check is being drown On an account. The transactlon involve, number of steps starting with cmcrlng check details and

82

U rheberrcc htl lch gcsc h utztes Iv! ateri"

Chovter 4.: Tmr~srrrl'i"OI.l-5

updating two accounts for tile check amount. But, we must stop the transaction if the accouru does not have suffkient funds.

In case when a process in J transactlon fails, any changes thai were made now by the rransacuon must be undone.

A transaction will allow us to indicate the beginning and ending steps of this logical grouping. if ali of the steps complete successfully, then any changes made along the way would be permanent, or committed. If "ny of (he stops fail, 111(, .,11 changes made would be undone, Or rolled back. Thi, way Alorni d Iy ensu res I hat a I the concl us i (}I\ of the tr a nS'1C I ion, these operations are either performed successfully (a successfu] ccrnrnit), or none of them are performed at all (a successful rollback). At the end of a transaction, atomicity would be violated if some, but no! all, of the operations completed.

Consisfllncy

All transactions interact with some d~tr)b~se to m~Hllpul~He inform.1.hon iH::(ording]}J. The dora is said to be in consistent Slate if il is in agmemenl with all the constraint, or rules defined for the database.

The consistency property of transaction says that if the system was in a consistent state when the transaction began it must be ina coos i sten t sta te wh en the tr a nsaction ends. Th is is regardl"" of w hel her I he Ira nsaci i on 5 ucceeds a nd is corn mi ned. or f" i Is a nd is roiled back

The consistency is assured by transaction manager and developer both. Transaction manager ensures that ACID property of transaction is lntact and Ihe developer ensures consistency by ,pecifying different constraints.

To maintain consistency of the database when a transaction is committed, the consistency of transactlon is validated by DBMS against JII the constraints defined before the changes made by transactions are reflected in database, If the result' do not ,ali"f)' the 'f'<1uirement5,. rhe Iran sactio n wll I be rolled back.

The consistency property of transaction makes it sure that the transaction is not going 10 leave system in an invalid stale. This makes transaction more reliable.

Isolation

This isolation property of the transactlon makes .it sure rhat the <klta which ls being interacted by it transaction 1$ not accessible by another transaction. f! means. no other nansaction is allowed t~J access data tilt one transaction working over il. completes.

The rsolauon is important 10 support concurrent ilCC~SS 10 data. The probability of getting error and corruption ol data is high in a concurrent 5.YStW1"1, if the Ihi.n,gs are not controlled properly.

The transaction manager takes the responslbil ily of en,uri"ll isolation and managing concurrent execunon,

T msactlon lsolatlon specifies that the outside world is not able to see the intermediate state of a transaction. Outside programs viewing the data objects involved in a transaction must not see the modified data objects Unlil after the transaction hJS been committed. Trcnsacnon isolation is a complex science in it",lf" and is largely beyond the 'mpe of this discussion, but sufflce it 10 say that EIB server provide" typically offer conflgurable isolation settings Ihal tet you choose Ine degree 1.0 which resources within " tran,ac[ioh', scope can see each other" pending change, •.

83

U rheberrcc htl lch gesc h utztes Iv! ateri"

3,0;"

and changes that 'were committed externnlly but during the course of the (dirt;' reads). There is no standard isolation setting. so portable applications particular coniigurati'on in their runtime environment

Durability

The changes that result when a transaction is commuted must become visible to the applications. The durabil ity property of transactions define, that ,111 the changes made transaction must recorded in some permanent storage. These changes (an be recorded in log files known as fransaction log. A transactlcn log is the listjng of all the changed some transactlon to the database. This helps in recovering you data to previous valid case of some data lose due to some error or corrupuon,

Transaction Models

A transaction model is a generalized framework that describes" class of transaction s, many different types of and uses lor transactions, How a transaction is used and structured typically falls into one of many transactional models. We'll take a look at namely:

o Flat transactions

Il Nested tra nsact ions a Cha i ned tr an sact io ns IJ Saga transactions

We will start with nat transactions.

flat Transactions

Flat transactions are simplest type of transaction, It is a single unit of task which is a group number of steps. If any of the steps of this transaction fails, (he transaction is rolled back. transactions arc standard for database operations and EJBs.

Nost8t1 Transactions

Nested transactions as the name ,uggest;s the transaction, are further nested inside transaction, In this model, a transaction A can have another transaction B as one of process grouped together to make transaction A. In other words, a transaction have transactions. A sub-transaction is either a nat: transaction or another nested transaction.

Fig.EJIJ.-4,1 shows an example of nested transaction, Transactlon A begins which Transaction B. Transaction B. in turn. invokes nrst Transaction C, then Transaction D.

84

U rheberrec hll lch gesc h utztes Iv! aleri"

L,J

L,J

I I I I

Flg.EJB ..... l

Another example of ne5le<J IronS.Klions mighl, be an airline reservation system. Let's say th,1I we wan I to book a Ilight from New Delhi to Mumbai. Our first transaction m entails our aUempt to book a direct flight. No direct nights arc available. so our transaction fJi 15. This is a 1111 trarrsartlon, We then start a new transaction (U) and try to find a flight that is available between New Delhi and Pune, We want 10 hold this reservation, so we keep the transaction open. We then begin a new transaction (VI, with our current one, that will attempt to book d irighl from Pune to Mumhai. There are no direct nighl, between the two dtie" so our tran,aClion r"ils and rolls back. However, since the transaction is localized ~l Pune, we will nOI. lose the New Oelh i booklng. Remember. nested transactions do not roll back the transaction in 'which Ihey are contained. Another transaction (WJ i s s taned, this time attempting to book", Oight between Pune and Hydorabad. We are successful in finding a reservation, 50' we hold transaction W open. Finally, we initiate a new transaction IXI in hope, of finding a Hight from Hyderabad to Mumbai. If we are successful. we commit rransactlon X, Transaction W checks, the status of transaction E and, seeing that it was successful, W commits. This conttnues with \Vls parenl, transactlon U, and then T. With all of the transactions committed (T, U, W, & XI, we have booked our flight. If we had decided that four flighls were too many and decided 10 scrap the whole an"ir and take the train instead, X would roll back, W would see thill X failed and. as part of a business rule 10 not ;or;r;epl thls m.)!,), layovers. would roll back, and the entire tree of transactions {T, U, W, & El had been aborted and the entire transaction cancelled.

Chained Transactions

A series of transactions are referred as Serial transacttons or Chained transactions. These transactions are related logethe, and contiguous. The next transactiun in a series of transactions

85

U rhcberrec htl lch gesc h utztes M a\c,i"

EjB 3,0 '"

re lies on 111 e resu I ( 01 prey lou, !!lUI mple. The set 01 transactions are at Once subrn i ned to transaction manager, The transaction manager executes each transaction in a series one by

I n a cha i ned Ira nsact i on, a U resources bel ng used by a Ira nsacti on in tn e series are

make I hem a va ;lab I e for the next transacti 0 n in the serl es, This ls achi eved by us i ng C ommi and baqd.n'r'r-an sac t ion (J in a single step, The resources which are not required transaction in 11m series are released, An)' ether transaction other than included io the transaction being executed can 001 access the data being used by these chained

transaction in the series fails, only the concurrently running transactions are rolled

The Fig.EIB-4 ,2 gives you an idea of Ihe gener,,1 progresslon through a chain of

Urh 00 reel 111'eh gescil JI,te5 SII I

fig.EJB-4.2

The d isa dvan tage of cha i ned Ira n sacuons ls I ha tih "y can b lock a la rge set of valu ab I e S.OI this should be taken Care whITrnib~}r~bc~tich gr~ch~~£811Ia a chained transaction,

Saga Irsnsections

They ore I"ng lived rransacuons slrnllar' to chamed rransactions. Hence, they are also of multiple transactions. But here each transaction has a corresponding transaction. When any of the transaction [ails, the cornpensatlng transactloos for all execulE'd tr ansa ct loris are i nvoked automat i ca II y by tra nsacti on mil n age,. So, before transaction is starred lhe relauonsbips belween transactions and Iheir compensate sh 0 ul d be ide n li fi edto the tra nsac I ion rna nager.

The state diagram here lllusuates J sample ><lga thal consists of three transactions:

86

Urr~b rrechtl: 11 g sohii:"1 "~\ rta

Distributed Transactions

Chapter 4.: Tm'l~uttiontt

A distributed tr{;lnsactfor; is· a rransactton whose CO ntex I Spar1S more Ih.10 one resource and/o. whose context is propagated or shared by more than one component. In other word" when the operations in " transaction are performed ~crOS5 database or other resources that reside on ,eparale computers or processe" this is known as a distributed transaction. Dis.tributed transactions support scenanos such as:

o A component needs to communicate with multiple resources within the same atomic

operation.

o Multi p le cornponcn ts need to ope rate wi t hin the $<1 me~ a to m ic opera! i on.

A distributed transaction Dilen span, multiple resource manag<;,"_ Each resource manag~r may be hosted on a heterogeneous processing node, manage, its own thread, of control, and hils a different resource adapter. According to Dlstributed Transaction Modd, a distributed transaction model is more complex than local: one; more participants are involved ina distributed transacuon model. The following Ii>! describes the participants in a distributed transaction:

o Transaction Or;gin~to" The client initiates the transaction. It Can be a java application in the client tier, a servlet in the Web tier, or a session bean in the EJB tier. It also can be a JMS producer/consumer in the Web tier or the Ela tier.

a Transactloe Manager: Manages transactions on behalf of the originator. It enforces the tr~nsaction ACID properties by coordinating access across oil parlicipating resource managers. When resource manager, fdil: during transactions, transaction managers help resource managers decide whether to commit or roll back pending transactions. JTA implement' the transaction manager in 12EE architecture.

o RecQ~erabre Resource, Provides persiltenl storage ior transaction data to ensure durability oi the transaction. In most cases, this is often a database or a flat file resource,

o Re.soutc<;, Manage" One of the aforementioned transaction-aware Iypes_ This can manage" DBMS, a iMS provider, or a jCA resource,

The Fig.EIB.4.4 summarizes the protocol, and lnteractions among oil participants 01 a distributed transaction.

~'I::~~

'""""'~'"

Flg .. EJII4 .. 4

87

U rheberrec htl lch gC5C h utztes Iv! aleri"

The Two-Phase Commit Protocol

To periorm J distrtbuted transaction, the transactlon manager coordinates the transaction exec ut i on ac ross mu I t i pi e resource rna nagers, B('C ause all parti (lpan1 reso urce rna nagers are not aware of each other, an algorithm has been establ tshed, a, a standard protocol, to control the interactions or all participants. The Two-Phase Commit (2PQ protocol enforces tneACID propertl es and is i rnple merited into 1\"'0 ph" ses:

o Phase 1: This is the preparation phase, The Iransaction manager, or cocrdlnaior, asks each resource manager to be prepared to commit (also called vote to commit), This in v olves a>signing locks to shared resources without actually wr.ihng data 10 permanent storage. Each resource manager replies with its readiness 10 execute.

'0 Phase 2: II all the resource manager. reply- with successful preparation, the transaction m"nager requests all to comrnil their changes; otherwise, it tells them all to roll back and indicate, transaction failure to the appllcanon, The rransactlon will succeed if and only if a.11 resource m~1n;J;gefs. commit successfully.

Transaction Support in EJB 3.0

EJB 3.0 hand I,,, transaction management through Java Transactlon API UTA) which i, to be. discussed ,00n in this chapter. In EJB 3.0, you can use transactions by two ways.

I~ The first way is io declaratlvely manage transaction ",ing Container. Managed Transactions (CMT).The CMT Can be implemented by usin~ annotations or the Deployment Descriptor.

o The second way is to programmatically manage transaction by USing Bcan-Managed Transact-ion, IBMTJ.The aMT requires you 10 manage transactions explicilly.

Java Transaction API (JTAI

With ,J genera I u ndersta ndl ng of tra nsact ion, under you, be I t, i I.'S Ii me to look mare at how transactions Me supported by Ihe EJB planorm. TOl provide the transactional capabilili.,. needed by an EJB application, an EJB container is required to SUPPOlrt the high.level interface defined by the Java T ransa cuon API liT A) for Ira nsacti on demarcation. The best way to understand JTA and ilS role ill EJB is to look at how il relates to several key specifications. on transacnon processing. This background will help you see the big picture into which ITA lits and get. a quick irnrodcctlon to the le,rminology involved in describing transactional systems,

The JTA deflnes a set of J.W;l intertaces thai specify how a transaction manager cornrnunlcates with an apphcatlon, a resource manager, and the application server in .12EE archttecture, The

p ri mary interi" eel fo un di n th e JT A consist Olf: .

CI The jmva:x. r.:ransac'Lio!l"l ~ user-r nee r face inrerface. (J The j avsx ~ tr~nse.c t Lon ~...:a r XA_Re.s,ou.!ce interlace.

Lt The jav~x .l:.ran:::ii-t:!Ic"Cio:n ."i'!:'at~sacticn~1;a.nagler interface.

As an EJB developer, yOlU will probably need to know about only one JTA interface .• j a vax , t ~ansaction. User4rransact.ion. This is because the container takes care of most Irans3C1iOln management details behind the scenes,

ss

U rhcberrec htl lch gesc h utztes M ateri"

The UserTransaclian Interface

The j ave x . t ranse ct ion" Use <'!'ran sacr ion inlerf'ce provides oppllcasions with the "bi I it y to demo rca te t ra nse Clio n bou n da ri es. II prov i de, I ypica I mel hods for begi nn i ng, co m m itti ng, and ro 1:1 i ng back top- I evel tr ansa eli 0 ns. Ne, ted tra nsact ions are not su pported an d i i the call.ing thread is already associated with a transaction begin throws a NotSupported~xception. When a new transaction is created, UserTransactton automatically associates it with ihe invoking thread, meaning thai the threads' nction or the current transactlon i:s modified. 1\1 any given time, a thread's transaction context may either be null or refer 10 a specific global transaction. Multiple threads may be associated with the same global transaction,

The Java EE 5 specification indicates that component, that may use the IJser'!' r ans ac cion interlace tsuc has EI B, Servlet, an d IS PI must access the prov i d ed ref ere nee by perle rrn i ng a IN D I name lookup fo' "java: comp/Use r'r r ans ect Lon". Here', an example:

An EIS ,may also access the User'lransaction implementation vi" the EJBCont e x t , qe t uae r r'r anaec t ion II method. Any such reference is only valid within the component instance that performed the lookup. We will discuss more about Use'rTransactioTl interface in the secucn Bea n~MllnJged transacricns.

Container.Managed Transactions

In a conlainer.manased transacuon, the EI B contalner monag", Ih e transaction demarcation for each method 01 the bean. Transaction behavior is described in the bean', Deployment Descriptor or in the annotated do.", Transaction attributes determine how the EJB container handles transactions with each bean', mel hod lnvoratlon, Each method con be asscciated with only a single transaction, A transacnon begins just before Ihe method starts, and commits just before it exit" Nol 31.1 the methods of the bean are associated with transactions, only those spccilied in the bean's Deployment Descriptor by transaction attributes. The following section introduces the transaction attributes that are vital in configuring the bean's methods par(idpal.ing in a conta i ner -man aged I ran Side, i on,

Enterprise lov"Beans support six type, of transactional attributes: n REQUIR£D

Cl REQUIRES_NEW

o MANDATORY

o SIJPPORTS

a NOT' SUPPOR'!'E[)

89

[183.0 in Simple 51"1"

o NEVER

REQUIRED

This transactional attribute defines that the given method is 10 execute always within a transartion. In case, the method is invoked within the context of some existing transaction, the same transaction is used otherwise a new transaction is created by container.

The new transaction created in l.hiS way starts when the method begins and comrons only after the method ends. In case of rollback, all changed ore undone and a RoLlback.Exception is thrown,

The required transaction operation is required when the method is involved in some serious data cha n ge whit h needs 10 be protected by a tr ansa CI ion.

REQUIRES_NEW

Setting Re'lu.ires_new transaction attributes assures that the method is always executed within a new transaction. A new transaction is created before the method is invoked .. II means that the method is going 10 be executed lnto its own transacticn and it's helpful in implementing local rollback and IOCJI com mil. Here, the local rollback and loca I commit mean that they do not affect outcome of other transactions outside the method.

If the method is invoked in coruext 01 some exi,ting transaruon, this transacucn is suspended and the new transaction is started, The suspended transaction is reinstated after the completion of new transaction.

MANDATORY

This is somewhat opposite to RCglU i:t"~d _New transaction attribute. Setting of this attributes assures that the method is going to be executed in the context of some pre-exi'ting transaction only. So it becomes mandatory, the client already has a transaction ",nning and the context is available to be propagated 10 your mel hod. In case there is not transaction context, the container throws a Transaction8.equiredEx.cepti,on or a TransactionRequiredLccalException,

We should use the Mandatory allrib"le when Our method needs to verify that the component was invoked within the context of a client-managed l_ransaction.

SUPPORTS

This transaction attribute assures that the method can be invoked with some existing transaction coniexi, however, if there is no transaction context, the method Can be invoked without a transaction.

In case, where we do not need to incur processing overhead or suspending and resuming an exi$ting transaction, we can use surpowrs attribute. We must also be sure about that" our method is either not causing Jny exception thai will signal a failure within the context of a transaction.

NOT_SUPPORTED

The !lot suopo .t.eo! transaction attribute defined to the container that the method should not be i nvokE.d ';"j th ina tra nsaction. If the method is i nvoked by usi ngsome ex isti nS tra nsactl On

90

U rheberrcc htl lch gesc h utztes Iv! ateri"

context, the transaction ",HI be suspended before the method is invoked. Any exception caused by the method is not going to affect this suspended transaction.

The Never transaction attribute represents Ih.>I. the method should never be invoked in context of a not her tra nsacti on. This s hou I d be used when we n eed 10 check I ha I I he met hod i sn ot invoked within a client managed transaction and the container is not going 10 attempt to provide a transact i on 10 r it.

This attrlbute is used when the given mel hod is nol capable enough to participate in a transaction. If the method is invoked and a transaction context exists, the COntainer wi ll throw a RemoteEl<ception or EJBEJ(ception lor remote andlocal clients respectively.

C MT u sl ng Annotated el ass

The EJB container provides built-in transaction rnnnagemern services thai are avai lable by default to session beans and MOBs. The containes demarcates transaction boundaries. and auiornaucally begins and commits transacttons based on, declaratlve metadata (XML file) provl ded by th e bea n developer.

When an EJB declares its transactional behavior in rnetadata, the container interposes on calls to the enterprise bean's methods and appl les transacnonal behavior at the session bean's method

providing a fixed set of option> that you can specify for each method. Th e default provided by the container is to check immediately before invoking the method, a transaction context ls associated with rhe current thread. II no transaction context is available, the container begins a new transaction before calLing the method. If a transacnon is available, the container allows the transaction 10 be propagated to the method call and make, it available to the method cede. Then, upon returning from the method invocation, the container check; again. ff the container was responsible lor creating a new transaction context, it automatically commits that transaction after the method is exited. If it didn't create the transaction, then it. allows (he transaction to continue unaffected. By interposing on the bean's method calls, the EJB container is able 10 appl)f transactional behavior at run time that was specified declaratively at development time.

We Can Implement CMT elther by using the annotated class Or by the Depl'oymenl Descriptor. we a re fi rst goi ng to i mplemen I il us i n g annota ted class. The foil owl ng code sn ippet show, hew eMT is implemented using annctaieo class:

91

fiB 3,0 Ju Simpl. 51,ps

Now look at the code the @'I'r"nsa.ctionM<!o~gemeot annotation specifies whether containermanaged transaction 01 bean-managed transaction is used lor a particular bean. tn Our example, we are using CMT, so the annotation ls defined as:

-~

II means that the corns iner should manage rransactlon on bean", behalf. II we leave il then the container will assume CMT because by default it is (MT, The next annotation is @T r~nsactionA t t r i bu te which defines the type of transaction attribute that is used on the methods, You can define 'eparate transactlon attributes for individual methods or you can define one annbute for several methods. The firSI @TransactionAttribut .. annotation specifies that a II ih e methods of I he De pa r t me n tMa na ge r Be a n have a Ira n sact i 011 aurlbu te of RequiresNe" by default. The second @TransactionA~~ribut .. annotation overrides the default setting (0 specify thai (he gettl"me () method has a Not Supported transaction attribute. MOBs support only (he REQUIRED and NOT_SUPPORTED attributes. We hod already discussed transactions attributes.

Implementing CMT using Deplovment Descriptor

You can also implement CMT by u'ing Deployment Descriptor_ In the XML Deployment Oescrlpror, ej b- j ar , »m.l , a <CGIl t a i na r-t rans act Lon > elemerH specifies Ihe transaction ami b uies for I he EJ B, desc r i bed in I he Dep I oy men! Descr i pt or, The Dep I oy men l Descr i pier implementation for the preceding annotated class is shown here:

92

Chapter 1: Tfj'm:wctjt:m~

ThiS Deployment Descriptor specifies the transaction attributes for the Trave lAgenL EJB. Each <con t a i ne r- transact ion> element spec-ties .,_ mel hod and lh.;)l parttcular method's, transactlon attribute. The first <container-transaction> clement specifies that "II methods have a transaction aurlbute of Requ i ~esNe,", by def,'url; I.he • is a wildcard that indicates 011 the methods of the nepe.r tmen tjce naqe r aean l'JB. The second <cont.e Ine r e t r en se ct Loo> element overrides the default selling 10 specify that Ihe ge tName I ) mel hod has a tlotSuppor ~ed transaction attribute.

N44t

Bean-Managed Transactions

In some cases the container man(lgC'('J 1r:.nsactions does '1101 provide the solunons which some enterprise bean, require, For example consider a cl ient who wants to Coli multiple methods on a session bean. without having each method COI1"1mil its work upon completion, to overcome this, EJ B P rovides a conven i en twa y to han die isola ti on of tra nsacti on eve n I,. Fi rst you have to turn off the con! a i ner ma na gecl serv i ces, wh ieh is done b)' s imp Iy s peel r yi ng rh e Tran5a.c c i onManagement Type 10 BEI\N using the foHowing annorarlon: @Trans"ctionManag;ement (T r-a nMctionMa ""gemen t Type. S<:.AN I

or assign (he equivalent metadata to the session bean in the ej b-' jar. xml fi le. Wit.h BMT isola t ion, th e EJ B conta inc, ,I i I I prov i des the Ira nsact. 0 n support to the boa n. Now the pri mary difference is that the enterpri,e beam now calls to begin, cornrnlt and rollback transactions explicitly. Any gi,ven enterprise bean must choose one plan or the other (eMT vs. I3MT demarcation) for its methods, both Iypes of beam may interact with each other within a single t ra nsa ction con tex t.

Ente~)fi,e beans thai manage their own transactions are f,requenlly referred to as Bean-Managed Transaction (BMT) beans, Entity bean, call never be BMT beans. OMT beans do 1101 declare tIO nsacrion attri b utes for the i r rneth ods, H ere's how a sessi on be" n declares tha t it mi II rna n age In e tra nsacti ons ex!' I i ci t I y, To isola te tra nsa c I ions. In en Ie rprls e bea n imp I em ems the javax. transaction. use r t'ransacr f on interface. This interface provides begin II , commi r (J, and rollback (J transact ion isolation methods to the bean. so that the fJB manages the transaction isolation explicitly.

In the example that follows a session bean by using BlvlT Jsotauon initiates a transaction in (me method. II is then propagated 10 subsequent mel hod Co lis until the transacuon lis (i"ally committed in a separate method, This can be done by specifying the T r~nsaction~!8n<tge rType \0 !lEAN which CJn be provided as shown in following snippet

i[llPort. ja'l/iillx.ejb. "" :

93

Sign up to vote on this title
UsefulNot useful