Wednesday November 16, 2005
Better practice in EJB handling exception Sometimes I get user's source code. Recently, I had a chance to study one J2EE application.
I was interested in one business method that creates new entity bean or finds existing one. This
method was implmented very disconsolately and threfore I decided to analyze this method and suggest
better solution.
The user has EJB module with many entity beans and one session bean. The session bean conducts as
session facade. Web clients communicate with this bean. This is common pattern in J2EE application when you have session facade in application tier and business delegate in web tier.
Session bean has one business method that has a paramater that represents composed transfer object
(AccountDTO has references to UserDTO and MestoDTO). The methods checks wheter entity bean exists and creates new one if not, see code:
public void createAccount(AccountDTO account) throws EJBException{
try {
MestoLocal mesto;
MestoDTO mestoTO = account.getMesto();
if(mestoHome.cityExists(account.getMesto().getId())){
mesto = mestoHome.findByPrimaryKey(account.getMesto().getId());
}else{
mesto = mestoHome.create(mestoTO.getId(),mestoTO.getDescription());
}
UzivatelLocal uzivatel = uzivatelHome.findByPrimaryKey(account.getUzivatel().getId());
accountHome.create(account.getIdAccount(),account.getAmount(),uzivatel,mesto);
In this snapshot cityExists home method of Mesto entity bean is invoked. The home methods return true if appropriate bean exists and false if not. This home methods invokes select method that has folowing EJB-QL query:
SELECT COUNT(o) FROM Mesto o WHERE o.id = ?1
I think that implementation is very ugly, home methods are not intended for this purpose. They should be used for business logic that is not specific to an entity bean instance. I guess that using home method for this is uselessly.
try{
mesto = mestoHome.findByPrimaryKey(account.getMesto().getId());
}catch(ObjectNotFoundException ex){
mesto = mestoHome.create(mestoTO.getId(),mestoTO.getDescription());
}
The home and select methods are not needed in this case. What's your opinion for the originall method?
Posted by pblaha
( Nov 16 2005, 05:22:05 PM CET )
Permalink
Comments [0]