新版本中spring與hibernate整合dao層調用session的方法

來源:互聯網
上載者:User

(選自:《Beginning Hibernate》及《spring-framework-3.0.5.RELEASE reference》)

在spring和hibernate整合架構中,session factory被配置為一個spring
bean,以前版本會利用HibernateDaoSupport和HibernateTemplate這兩個類,在新版本中可直接利用方法
session factory的getCurrentSession()返回當前事務的session。

如:

1. public List<Paper> getAll() {<br /> 2. Session session = this.sessionFactory.getCurrentSession();<br /> 3. List<Paper> papers = (List<Paper>)session.createQuery("from Paper").list();<br /> 4. return papers;<br /> 5. } Hibernate 3.0.1開始具有有contextual sessions特性,這樣hibernate為每個交易管理一個當前session。之前都是spring的相關支援類來實現這個功能。我們推薦使用這種方式。優點:只依賴於hibernate,不再需要spring相關類。減小入侵性。(Hibernate 3 has a feature called contextual sessions, wherein
Hibernate itself manages one current
Session
per transaction. This is roughly
equivalent to Spring's synchronization of one Hibernate
Session
per transaction. A corresponding
DAO implementation resembles the following example, based on the plain
Hibernate API:)Spring的 LocalSessionFactoryBean為其事務策略 支援Hibernate的
SessionFactory.getCurrentSession() 方法, 返回當前spring管理的事務session,(Spring's LocalSessionFactoryBean supports Hibernate's
SessionFactory.getCurrentSession() method for any Spring transaction strategy, returning
the current Spring-managed transactional Session even with HibernateTransactionManager.)

public List<Paper> getAll() {<br />Session session = this.sessionFactory.getCurrentSession();<br />List<Paper> papers = (List<Paper>)session.createQuery("from Paper").list();<br />return papers;

With your session factory configured as a Spring bean, you can now go on to create DAOs that take
advantage of Hibernate’s functionality. Previous versions of Spring and Hibernate required the use of
the HibernateDaoSupport class and/or HibernateTemplate class to form the basis of your DAOs; however,
recent versions of Spring and Hibernate have eliminated the need for these classes. Hibernate now
supports a getCurrentSession() method on the SessionFactory that returns a Session object that is
associated with the current transaction.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.