我的网络应用程序有很多服务表/实体,例如payment_methods
, tax_codes
, province_codes
, etc.
每次添加一个新实体时,我都必须编写一个 DAO。问题是,基本上,它们都是相同的,但唯一的区别是实体类本身.
我知道 Hibernate 工具可以自动为我生成代码,但我现在不能使用它们(不要问为什么),所以我正在考虑一个通用DAO。有很多关于这方面的文献,但我无法将各个部分组合在一起并使其与 Spring 一起工作。
我认为这都是关于泛型的,它将有四种基本方法:
listAll
saveOrUpdate
deleteById
getById
就这样。
问题:
什么是最佳实践不重新发明轮子?还没有现成的东西可以用吗?
这是我的
@Component
public class Dao{
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
public <T> T save(final T o){
return (T) sessionFactory.getCurrentSession().save(o);
}
public void delete(final Object object){
sessionFactory.getCurrentSession().delete(object);
}
/***/
public <T> T get(final Class<T> type, final Long id){
return (T) sessionFactory.getCurrentSession().get(type, id);
}
/***/
public <T> T merge(final T o) {
return (T) sessionFactory.getCurrentSession().merge(o);
}
/***/
public <T> void saveOrUpdate(final T o){
sessionFactory.getCurrentSession().saveOrUpdate(o);
}
public <T> List<T> getAll(final Class<T> type) {
final Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(type);
return crit.list();
}
// and so on, you shoudl get the idea
然后您可以在服务层中像这样访问:
@Autowired
private Dao dao;
@Transactional(readOnly = true)
public List<MyEntity> getAll() {
return dao.getAll(MyEntity.class);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)