Tải bản đầy đủ - 0 (trang)
8 The ejbLoad( ) and ejbStore( ) Methods

8 The ejbLoad( ) and ejbStore( ) Methods

Tải bản đầy đủ - 0trang

try{

con=this.getConnection();

ps=con.prepareStatement(

"updateShipsetname=?,capacity=?,"+

"tonnage=?whereid=?");

ps.setString(1,name);

ps.setInt(2,capacity);

ps.setDouble(3,tonnage);

ps.setInt(4,id.intValue());

if(ps.executeUpdate()!=1){

thrownewEJBException("ejbStore");

}

}

catch(SQLExceptionse){

thrownewEJBException(se);

}

finally{

try{

if(ps!=null)ps.close();



if(con!=null)con.close();

}catch(SQLExceptionse){

se.printStackTrace();

}

}

}



Exceptforthefactthatwearedoinganupdateinsteadofan

insert,thismethodissimilartotheejbCreate()methodwe

examinedearlier.WeuseaJDBCPreparedStatementto

executetheSQLUPDATEcommand,andweusetheentity

bean'spersistencefieldsasparameterstotherequest.This

methodsynchronizesthedatabasewiththestateofthebean.

EJBalsoprovidesanejbLoad()methodthatsynchronizesthe

stateoftheentitywiththedatabase.Thismethodisusually

calledatthestartofanewtransactionorbusiness-method

invocation.Theideaistomakesurethatthebeanalways

representsthemostcurrentdatainthedatabase,whichcould

bechangedbyotherbeansorothernon-EJBapplications.

HereistheejbLoad()methodforabean-managedShipBean

class:

publicvoidejbLoad(){



IntegerprimaryKey=(Integer)context.getPrimaryKey();



Connectioncon=null;

PreparedStatementps=null;

ResultSetresult=null;

try{

con=this.getConnection();

ps=con.prepareStatement(



"selectname,capacity,tonnagefromShipwhereid

ps.setInt(1,primaryKey.intValue());

result=ps.executeQuery();

if(result.next()){

id=primaryKey;

name=result.getString("name");

capacity=result.getInt("capacity");

tonnage=result.getDouble("tonnage");

}else{

thrownewEJBException();

}

}catch(SQLExceptionse){



thrownewEJBException(se);

}

finally{

try{

if(result!=null)result.close();

if(ps!=null)ps.close();

if(con!=null)con.close();

}catch(SQLExceptionse){

se.printStackTrace();

}

}

}



ToexecutetheejbLoad()method,weneedaprimarykey.To

gettheprimarykey,wequerythebean'sEntityContext.Note

thatwedon'tgettheprimarykeydirectlyfromtheShipBean's

idfield,becausewecannotguaranteethatthisfieldisalways

validtheejbLoad()methodmightbepopulatingthebean

instance'sstateforthefirsttime,inwhichcasethefieldswould

allbesettotheirdefaultvalues.Thissituationwouldoccur

followingbeanactivation.Wecanguaranteethatthe

EntityContextfortheShipBeanisvalidbecausetheEJB

specificationrequiresthatthebeaninstance'sEntityContext

referencebevalidbeforetheejbLoad()methodcanbe



invoked.

AtthispointyoumaywanttojumptoChapter10andreadthe

sectioncalled"EntityContext"togetabetterunderstandingof

theEntityContext'spurposeandusefulnessinentitybeans.



9.9TheejbRemove()Method

Inadditiontohandlingtheirowninsertsandupdates,beanmanagedentitiesmusthandletheirowndeletions.Whena

clientapplicationinvokestheremovemethodontheEJBhome

orEJBobject,thatmethodinvocationisdelegatedtothebeanmanagedentitybycallingejbRemove().Itisthebean

developer'sresponsibilitytoimplementanejbRemove()

methodthatdeletestheentity'sdatafromthedatabase.Here's

theejbRemove()methodforourbean-managedShipBean:

publicvoidejbRemove(){

Connectioncon=null;

PreparedStatementps=null;

try{

con=this.getConnection();



ps=con.prepareStatement("deletefromShipwhereid=

ps.setInt(1,id.intValue());

if(ps.executeUpdate()!=1){

thrownewEJBException("ejbRemove");

}

}

catch(SQLExceptionse){



thrownewEJBException(se);

}

finally{

try{

if(ps!=null)ps.close();

if(con!=null)con.close();

}catch(SQLExceptionse){

se.printStackTrace();

}

}

}



9.10TheejbFind()Methods

Inbean-managedpersistence,thefindmethodsintheremote

orlocalhomeinterfacemustmatchtheejbFind()methodsin

theactualbeanclass.Inotherwords,foreachmethodnamed

find()inahomeinterface,theremustbea

correspondingejbFind()methodintheentitybean

classwiththesameargumentsandapplicationexceptions.

WhenafindmethodisinvokedonanEJBhome,thecontainer

delegatesthefind()methodtoacorrespondingejbFind()

methodonthebeaninstance.Thebean-managedentityis

responsibleforlocatingrecordsthatmatchthefindrequests.

TherearetwofindmethodsinShipHomeRemote:

publicinterfaceShipHomeRemoteextendsjavax.ejb.EJBHome{



publicShipRemotefindByPrimaryKey(IntegerprimaryKey)

throwsFinderException,RemoteException;

publicCollectionfindByCapacity(intcapacity)

throwsFinderException,RemoteException;

}



HerearethesignaturesofthecorrespondingejbFind()

methodsintheShipBean:

publicclassShipBeanimplementsjavax.ejb.EntityBean{



publicIntegerejbFindByPrimaryKey(IntegerprimaryKey)

throwsFinderException{}

publicCollectionejbFindByCapacity(intcapacity)

throwsFinderException{}

}



Asidefromthenames,there'sasignificantdifferencebetween

thesetwogroupsofmethods.Thefindmethodsinthehome

interfacereturneitheranEJBobjectimplementingthebean's

remoteinterfaceinthiscase,ShipRemote--oracollectionofEJB

objectsintheformofajava.util.Enumerationor

java.util.Collection.TheejbFind()methodsinthebean

class,ontheotherhand,returneitheraprimarykeyforthe

appropriatebeaninthiscase,Integeroracollectionofprimary

keys.Themethodsthatreturnasinglevalue(whethera

remote/localinterfaceoraprimarykey)areusedwheneveryou

needtolookupasinglereferencetoabean.Ifyouarelooking

upagroupofreferences(forexample,allshipswithacertain

capacity),youhavetousethemethodthatreturnseitherthe

CollectionorEnumerationtype.Ineithercase,thecontainer

interceptstheprimarykeysandconvertsthemintoremote

referencesfortheclient.



TheEJBspecificationrecommendsthatbean-managedpersistence

beansusetheCollectiontypeinsteadoftheEnumerationtype.This

recommendationismadesothatBMPbeansaremoreconsistentwith

CMPbeans,whichuseonlytheCollectiontype.TheEnumeration

typeisanartifactofEJB1.0and1.1andismaintainedforbackwards

compatibility.



Itshouldn'tcomeasasurprisethatthetypereturnedwhether

it'saprimarykeyoraremote(orlocal)interfacemustbe

appropriateforthetypeofbeanyou'redefining.Forexample,

youshouldn'tputfindmethodsinaShipEJBtolookupand

returnCabinEJBobjects.Ifyouneedtoreturncollectionsofa

differentbeantype,useabusinessmethodintheremote

interface,notafindmethodfromoneofthehomeinterfaces.

TheEJBcontainertakescareofreturningtheproper(localor

remote)interfacetotheclient.Forexample,theShipEJBmay

definealocalandaremotehomeinterface,bothofwhichhave

afindByPrimaryKey()method.WhenfindByPrimary()is

invokedonthelocalorremoteinterface,itwillbedelegatedto

theejbFindByPrimary()keymethod.Afterthe

ejbFindByPrimaryKey()methodexecutesandreturnsthe

primarykey,theEJBcontainertakescareofreturninga

ShipRemoteorShipLocalreferencetotheclient,dependingon

whichhomeinterface(localorremote)wasused.TheEJB

containeralsohandlesthisformulti-entityfindmethods,

returningacollectionofremotereferencesforremotehome

interfacesorlocalreferencesforlocalhomeinterfaces.

BothfindmethodsdefinedintheShipBeanclassthrowan

EJBExceptionifafailureintherequestoccurswhenanSQL

exceptionconditionisencountered.findByPrimaryKey()

throwsanObjectNotFoundExceptionifnorecordsinthe

databasematchtheidargument.Thisisexceptionshould

alwaysbethrownbysingle-entityfindmethodsifnoentityis

found.

ThefindByCapacity()methodreturnsanemptycollectionif

noSHIPrecordswithamatchingcapacityarefound;multientityfindmethodsdonotthrowObjectNotFoundExceptionsif

noentitiesarefound.



Itismandatoryforallentityremoteandlocalhomeinterfaces

toincludethefindByPrimaryKey()method.Thismethod

returnstheremoteorlocalinterfacetype(ShipRemoteor

ShipLocal).Itdeclaresoneparameter,theprimarykeyforthat

beantype.Withlocalhomeinterfaces,thereturntypeofany

single-entityfindermethodisalwaysthebean'slocalinterface.

Withremotehomeinterfaces,thereturntypeofanysingleentityfindmethodistheremoteinterface.Youcannotdeploy

anentitybeanthatdoesn'tincludeafindByPrimaryKey()

methodinitshomeinterfaces.

Followingtherulesoutlinedearlier,wecandefinetwoejbFind(

)methodsinShipBeanthatmatchthetwofind()methods

definedintheShipHomeRemote:



publicIntegerejbFindByPrimaryKey(IntegerprimaryKey)throwsF

Connectioncon=null;

PreparedStatementps=null;

ResultSetresult=null;

try{

con=this.getConnection();



ps=con.prepareStatement("selectidfromShipwhereid

ps.setInt(1,primaryKey.intValue());

result=ps.executeQuery();

//DoestheshipIDexistinthedatabase?

if(!result.next()){



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

8 The ejbLoad( ) and ejbStore( ) Methods

Tải bản đầy đủ ngay(0 tr)

×