休眠:CRUD 通用 DAO [英] Hibernate: CRUD Generic DAO
问题描述
我的网络应用有很多服务表/实体,例如payment_methods
、tax_codes
、province_codes
等
My web application has got a lot of service tables/entities, such as payment_methods
, tax_codes
, province_codes
, etc.
每次添加新实体时,我都必须编写一个 DAO.问题是,基本上,它们都是相同的,但唯一的区别是实体类本身.
Each time I add a new entity, I have to write a DAO. The thing is that, basically, they are all the same, but the only difference is the entity class itself.
我知道 Hibernate 工具可以自动为我生成代码,但我现在不能使用它们(不要问为什么)所以我在考虑 通用 DAO.有很多关于这方面的文献,但我无法将各个部分放在一起并使其与 Spring 一起使用.
I know that Hibernate tools can generate the code for me automatically but I can't use them now (don't ask why) so I'm thinking of a Generic DAO. There's a lot of literature about that but I can't put pieces together and make it work with Spring.
我认为这都是关于泛型的,它将有四种基本方法:
It's all about generics I think, it will have four basic methods:
listAll
saveOrUpdate
deleteById
getById
仅此而已.
不重新发明轮子的最佳实践是什么?不是有什么可以使用的吗?
What's the best practice for not re-inventing the wheel? Isn't there something ready to use, yet?
推荐答案
这是我的
@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
然后你可以像这样在服务层访问:
and you can then access like so in service layer:
@Autowired
private Dao dao;
@Transactional(readOnly = true)
public List<MyEntity> getAll() {
return dao.getAll(MyEntity.class);
}
这篇关于休眠:CRUD 通用 DAO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!