Tuesday, September 23, 2008

GWT: convert database objects to DTO object

Google web toolkit operates on DTOs (Data Transfer Object) in the front end. Every time data is retrieved from the database, it has to be converted to DTO objects before it can be used in the front end. Below code illustrates how to convert from database objects to DTOs:

In the service implementation class, externd HibernateRemoteService class:
public class MyServiceImpl extends HibernateRemoteService implements MyService,
{
public MServiceImpl()
{
XmlBeanFactory xml = ApplicationContextFactory.getXmlBeanFactoryInstance();
setBeanManager((HibernateBeanManager) xml.getBean("hibernateBeanManager"));
myDao = (MyDao) xml.getBean("myDao");
}
private MyDao myDao;
public List fetchAll()
{
List myList = organizationDao.fetchAll();
List dtos = ConvertToDTO.clone MyObject ListToDTO(getBeanManager(), myList);
return dtos;
}
}


Create a method as follows:
public static List cloneMyObjectListToDTO(HibernateBeanManager beanManager, List myList)
{
List< MyObjectDTO > dtos = new ArrayList< MyObjectDTO >();
for (MyObject obj : myList)
{
MyObjectDTO organization = (MyObjectDTO) beanManager.clone(org1);
dtos.add(organization);
}
return dtos;
}


At this point you can make a call from the front end to the Asynchronous method to call the service implementation. This will allow you to get a DTO objects that are converted from the back end.