2011-11-22 53 views
5

我的Spring + Hibernate配置文件很小且超级紧凑。我使用自动扫描来查找我的模型实体/道数。使用注解书写Spring Spring Hibernate的DAO

我不想为我的层次结构中的每个实体都编写一个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); 

这是不切实际的?

回答

5

使用泛型,你可以尝试这样的事:

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

} 

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

你应该能够再使用

@Autowired 
private GenericDAO<Car> carDao; 
+0

我喜欢这个想法,但它的工作?我期望类型擦除会导致重复的bean定义,虽然没有检查这个虽然... – seanhodges

+1

搜索周围,它看起来像你可以解决使用子接口擦除:http:// stackoverflow。com/questions/502994/spring-ioc-and-generic-interface-type – seanhodges

+0

为了澄清一下,SessionFactory上的Autowired会在Spring中自动调用Hibernate的SessionFactory,对吗?但是如果我的CustomHibernateDaoSupport使用调用setSessionFactory(sessionFactory)的Autowired方法来扩展org.springframework.orm.hibernate3.support.HibernateDaoSupport。所以默认情况下,其他dao的会话被配置为由Spring自动管理......这些多个“会话”是否会带来性能问题? – sloven

2

自动装配在你的控制器和服务类的DAO您可以结合Spring/Hibernate with JPA,它提供了EntityManager了大量的基本持久性任务:

@Service 
public class CarService { 

    @PersistenceContext 
    private EntityManager em; 

    public void saveCarAndLease(Car car, Lease lease) { 
     em.persist(car); 
     em.persist(lease); 
    } 
} 

它也将处理事务和简单的查询,而无需编写DAO。对于更复杂的操作,你仍然可以编写一个DAO并回退到Hibernate的SessionFactory(虽然JPA也是一个选项)。

一些教程建议您仍然应该编写DAO来抽象JPA管道。然而,我个人认为这是不必要的(JPA的集成足迹非常小),实际上这也是Spring Roo处理幕后数据层的方式。

1

您是否试过使用弹簧数据。我的意思是说Spring JPA您可以在其中使用存储库。
您可以避免为每个实体编写所有东西。