小编典典

使用注释使用Spring Hibernate编写更少的DAO

hibernate

我的Spring + Hibernate配置文件很小而且非常紧凑。我使用自动扫描来找到我的模型实体/目标。

我不想为层次结构中的每个实体编写DAO + DAOImpl。

有些人可能有资格拥有自己的东西,就像他们与其他实体的关系复杂并且需要的不仅仅是基本的CRUD功能一样。但是其余的…

有什么办法可以绕过事实上的标准?

说,例如通用DAO,例如:

http://www.ibm.com/developerworks/java/library/j-genericdao/index.html

然后我可以做类似的事情

  GenericDao dao = appContext.getBean("genericDao");
  dao.save(car);            
  dao.save(lease);

注释可以吗?我不想在xml中配置任何内容。如果我不能完成上述操作,是否仍然可以使用一个类似GenericDaoImpl.java的程序:

 @Repository("carDao")
 @Repository("leaseDao")
 class GenericDaoImpl extends CustomHibernateDaoSupport implements GenericDao {
 ...
 }

然后

  GenericDao dao = appContext.getBean("carDao");
  dao.save(car);            
  dao = appContext.getBean("leaseDao"); //carDao is garbage coll.
  dao.save(lease);

这是实用的吗?


阅读 265

收藏
2020-06-20

共1个答案

小编典典

使用泛型,您可以尝试如下操作:

@Repository
@Transactional
public class GenericDAOImpl<T> implements GenericDAO<T> {

    @Autowired
    private SessionFactory factory;

    public void persist(T entity) {
        Session session = factory.getCurrentSession();
        session.persist(entity);
    }

    @SuppressWarnings("unchecked")
    public T merge(T entity) {
        Session session = factory.getCurrentSession();
        return (T) session.merge(entity);
    }

    public void saveOrUpdate(T entity) {
        Session session = factory.getCurrentSession();
        session.saveOrUpdate(entity);
    }

    public void delete(T entity) {
        Session session = factory.getCurrentSession();
        session.delete(entity);
    }

}

内容可能有所不同,但总的思想是适用的。

然后,您应该能够通过使用以下命令自动连接控制器和服务类中的DAO:

@Autowired
private GenericDAO<Car> carDao;
2020-06-20