關於hibernate的一些事

來源:互聯網
上載者:User

標籤:

關於hibernate的一些事 (此博文為http://my.oschina.net/u/555061/blog/506216後續)

1.簡單說一下SessionFactory、Session 源自: http://blog.csdn.net/javaloveiphone/article/details/8155340

1.1、Hibernate中SessionFactory對象的建立代價很高,它是安全執行緒的對象,被設計成可以為所有的應用程式線程所共用。通常,SessionFactory會在應用程式啟動時建立,一旦建立了SessionFactory將不會輕易關閉,只有當應用關閉時,SessionFactory才會關閉。
1.2、而Session的對象是輕量級的,它是線程不安全的。對於單個業務進程單個工作單元而言,Session只被使用一次。建立Session時,並不會立即開啟與資料庫之間的串連,Session只在需要進行資料庫操作時,才會擷取JDBC串連。因此,開啟和關閉Session,並不會對效能造成很大的影響。甚至即使無法確定一個請求是否需要資料訪問,也可以開啟Session對象,因為如果不進行資料庫訪問,Session不會擷取JDBC串連。
使用Spring管理hibernate的事務,在每個dao操作中使用SessionFactory.getCurrentSession()方法,該方法可以得到當前事務綁定的session。同時當前的Session和關聯的Hibernate事務被綁定到當前線程上,雖然session不是安全執行緒的,但是通過這樣的方式,每一個session都處於單線程中,避免session安全執行緒問題

1.3、不通過Spring管理事務,開啟事務的主動性:

在sessionFactory.openSession()中,Hibernate會初始化資料庫連接,與此同時,將其 AutoCommit設為關閉狀態,這就是說,從SessionFactory獲得session,其自動認可屬性就已經被關閉了,事務需要主動、顯示的調用才會生效,下面的代碼不會對事務性資料庫產生任何效果。
session=sessionFactory.openSession();
   session.save(user);
   session.close();
如果要使得代碼真正作用到資料庫,必須顯示的調用Transaction指令
   session=sessionFactory.openSession();
   Transaction tx = session.beginTransaction();
   session.save(user);
   tx.commit();
   session.close();

前面1、2點都是沒什麼問題,但是第3點事務的問題,我跟該博主意見不一致,首先Spring可以管理由Hibernate的SessionFactory產生的事務,所以通過Spring管理Hibernate的事務是可行的。其次,在開啟事務配置的同時,架構已經在自動幫你管理事務,也就是剛剛連續兩個操作,一個save一個sqlquery,由於sqlquery失敗導致save同時失敗復原(或者說就沒有commit的後續操作),而如果再使用session.beginTransaction()則會導致org.hibernate.TransactionException: nested transactions not supported錯誤,分析字面上的意思和根據本人查詢結果綜合來看,就是因為多次開啟事務導致錯誤,反過來說事務不需要在session.beginTransaction()的情況下才開啟,架構自動已經就在配置好以後就開啟了。


2.關於org.hibernate.MappingException: Unknown entity:錯誤

本人在發生的時候是由於沒有寫packagesToScan,以為可以在Spring自動包掃描的時候註冊hibernateEmployee這個包下面的類為bean,沒想到不行,需要在這裡寫

<bean id="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="packagesToScan">            <list>                <value>com.zhxjz.model.hibernateEmployee</value>            </list>        </property><property name="hibernateProperties"><props><prop key="dialect">${hibernate.dialect}</prop><prop key="show_sql">${hibernate.show_sql}</prop><!-- <prop key="hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> --></props></property></bean>



關於hibernate的一些事

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.