小编典典

Hibernate:CRUD通用DAO

hibernate

我的web应用程序已经得到了很多服务表/实体,如payment_methodstax_codesprovince_codes,等。

每次添加新实体时,都必须编写一个DAO。问题是,它们基本上是相同的,但是唯一的区别是 实体类本身

我知道Hibernate工具可以自动为我生成代码,但是我现在不能使用它们(不要问为什么),所以我想到了 Generic DAO
。关于这方面有很多文献,但我无法整理并使其与Spring一起使用。

我认为这全都是关于泛型的,它将有四种基本方法:

  • listAll
  • saveOrUpdate
  • deleteById
  • getById

就这样。


题:

不重新发明轮子的 最佳实践 是什么?还没有准备好使用的东西吗?


阅读 281

收藏
2020-06-20

共1个答案

小编典典

这是我的

@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);
    }
2020-06-20