充血模型设想实现(2010/07/30更新)
早两年,贫血模型和充血模型讨论的很热烈,但在具体实现时争论的比较多,关键还是由于Java不比动态语言那么容易去实现,如果能够在领域模型中动态添加相关访问数据库的方法,会是什么情况。。。
最近对操作字节码比较感兴趣,想在编译领域模型时,动态添加相关的字节码,达到丰富领域模型,同时需要hibernate 的支持,获取所有@Entity的领域模型,添加HibernateTemplate Field,借助aspectj,实例化领域模型时,注入hibernateTemplate。(Spring Roo就是这么实现的...)(如果需要注入其它的对象,同样如此)
// ASM 添加的方法:@Transientprivate HibernateTemplate hibernateTemplate;public HibernateTemplate getHibernateTemplate() {return hibernateTemplate;}public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {this.hibernateTemplate = hibernateTemplate;}
public void create() throws DataAccessException {hibernateTemplate.save(this);}public void createOrUpdate() throws DataAccessException {hibernateTemplate.saveOrUpdate(this);}public void delete() throws DataAccessException {hibernateTemplate.delete(this);}public Message find() throws DataAccessException {return hibernateTemplate.get(this.getClass(), id);}public void update() throws DataAccessException {hibernateTemplate.update(this);}public List<Message> findByProperty(String propertyName, Object value) throws DataAccessException {Assert.hasText(propertyName);Assert.notNull(value);StringBuilder buf = new StringBuilder();buf.append("FROM ").append(this.getClass().getSimpleName()).append(" WHERE ").append(propertyName).append(" = :condition");List<Message> entities = this.getHibernateTemplate().findByNamedParam(buf.toString(), "condition", value);return entities;}public List<Message> findAll() throws DataAccessException {return (List<Message>) hibernateTemplate.loadAll(this.getClass());}
final HibernateTemplate hibernateTemplate = new HibernateTemplate();HibernateTransactionManager transactionManager = new HibernateTransactionManager(HibernateSessionFactory.getSessionFactory());hibernateTemplate.setSessionFactory(HibernateSessionFactory.getSessionFactory());hibernateTemplate.afterPropertiesSet();transactionManager.afterPropertiesSet();TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);transactionTemplate.execute(new TransactionCallbackWithoutResult() {@Overrideprotected void doInTransactionWithoutResult(TransactionStatus arg0) {Message message = new Message();message.setHibernateTemplate(hibernateTemplate);message.setText("Hello World");message.create();List<Message> list = message.findAll();System.out.println(list.size() + "message(s) found");}});HibernateSessionFactory.getSessionFactory().close();