2012-01-03 78 views
0

而不是自動裝配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。

這種方法的優缺點是什麼?

回答

0

好的,沒關係。它不比第一種方法好或差,只是不同而已。

選擇你感覺的任何一個改善你的代碼可讀性,這是唯一真正的區別,它是主觀的。

0

是的,有可能並且毫不奇怪,Spring已經爲此提供了一個簡單的機制,使得您的DAO從HibernateDaoSupport延伸。然後您可以使用getHibernateTemplate()訪問模板。我能想到的唯一缺點是你的DAO與Spring特定的類相結合,但與經過良好測試的庫的耦合是可以的。另外,您已經直接參考HibernateTemplate

2

你可以這樣做,但如果你在使用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的更多信息。