hi,
i'm wanting to have my business objects populated with results from queries on loading but am wondering if i'm even going about it in the right way. I have an account object that i want populated with it's balance which is a calcuation of transactions and orders. i thought i could mabye use an interceptor to execute the queries whenever an object is loaded, but that seems to be causing some collection null pointers and i don't think it would be recommended by the hibernate team.
is there a better way to go about this? i need the objects to be populated automatically with the query calculations as they will be accessed themselves through querys, loads and associations, so i can't just use a dao to populate the extra fields.
thanks, cam
Code:
public class DataAccessInterceptor extends AbstractInterceptor implements BeanFactoryAware {
private BeanFactory fBeanFactory;
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames,
Type[] types) throws CallbackException {
DaoFactory daoFactory = (DaoFactory) fBeanFactory.getBean("daoFactory");
Object dao = daoFactory.getDataAccessObject(entity.getClass());
if (dao instanceof IDataInitializer) {
IDataInitializer initializer = (IDataInitializer) dao;
initializer.initialize(entity, id);
}
return super.onLoad(entity, id, state, propertyNames, types);
}
}
Code:
public class AccountDao extends HibernateDaoSupport implements IAccountDao, IDataInitializer {
public void initialize(Object entity, Serializable id) {
Account account = (Account) entity;
BigDecimal transactionTotal = (BigDecimal) getHibernateTemplate().find(TRANSACTION_TOTAL_QUERY, id).get(0);
if(transactionTotal == null)
transactionTotal = new BigDecimal(0);
account.setTransactionTotal(transactionTotal);
BigDecimal orderTotal = (BigDecimal) getHibernateTemplate().find(ORDER_TOTAL_QUERY, id)
.get(0);
account.setOrderTotal(orderTotal);
account.setAccountBalance(transactionTotal.subtract(orderTotal));
}
.....
}