Spring HibernateTemplate - 自动装配

问题描述:

而不是自动装配SessionFactory并创建HibernateTemplate,它可以自动装载HibernateTemplate吗?Spring HibernateTemplate - 自动装配

public class DaoImpl implements Dao { 

private HibernateTemplate hibernateTemplate; 

@Autowired 
public void setSessionFactory(SessionFactory sessionFactory) { 
    hibernateTemplate = new HibernateTemplate(sessionFactory); 
} 
... 
} 

而不是上面的代码,有没有像以下给出的罚款?

public class DaoImpl implements Dao { 

@Autowired private HibernateTemplate hibernateTemplate; 

... 
} 

并在XML中配置HibernateTemplate。

这种方法的优缺点是什么?

好的,没关系。它不比第一种方法好或差,只是不同而已。

选择你感觉的任何一个改善你的代码可读性,这是唯一真正的区别,它是主观的。

是的,有可能并且毫不奇怪,Spring已经为此提供了一个简单的机制,使得您的DAO从HibernateDaoSupport延伸。然后您可以使用getHibernateTemplate()访问模板。我能想到的唯一缺点是你的DAO与Spring特定的类相结合,但与经过良好测试的库的耦合是可以的。另外,您已经直接参考HibernateTemplate

你可以这样做,但如果你在使用Hibernate 3.0.1,你能避免休眠模板。以下是从Hibernate模板阿比here

NOTE: As of Hibernate 3.0.1, transactional Hibernate access code can also be coded in 
plain Hibernate style. Hence, for newly started projects, consider adopting the standard 
Hibernate3 style of coding data access objects instead, based on 
SessionFactory.getCurrentSession(). 

而且按照援引here

jboss的支持
If you plan to use the Spring Hibernate template, then don't. 
The Spring template were useful with Hibernate 2.x because of some mistakes we made 
the main one beeing checked exceptions. This is no longer the case for Hibernate 3.x. 
If you remove this exception wrapping necessity, Spring template are lust an overhead 
on top of the Hibernate API (hiding you the richness of the Hibernate API is some 
cases). 

Hibernate 3的一个主要变化是从checked变为unchecked exceptions。阅读here这篇文章和一个here的更多信息。