標籤:自動更新 .hbm.xml 知識 update http long 儲存 知識庫 space
<?
xml
version
=
‘1.0‘
encoding
=
‘utf-8‘
?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<
hibernate-configuration
>
<
session-factory
>
<!-- Database connection settings -->
<
property
name
=
"connection.driver_class"
>com.mysql.jdbc.Driver</
property
>
<
property
name
=
"connection.url"
>jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</
property
>
<
property
name
=
"connection.username"
>root</
property
>
<
property
name
=
"connection.password"
>admin</
property
>
<!-- SQL dialect -->
<
property
name
=
"dialect"
>org.hibernate.dialect.MySQLDialect</
property
>
<
property
name
=
"current_session_context_class"
>thread</
property
>
<
property
name
=
"show_sql"
>true</
property
>
<
property
name
=
"hbm2ddl.auto"
>update</
property
>
<
mapping
resource
=
"com/how2java/pojo/Product.hbm.xml"
/>
</
session-factory
>
</
hibernate-configuration
>
<property name="hibernate.hbm2ddl.auto">update</property>
協助文檔解釋為:
在SessionFactory建立時,自動將資料庫schema的DDL匯出到資料庫. 使用 create-drop時,在顯式關閉SessionFactory時,將drop掉資料庫schema.
取值 update | create | create-drop
(出自:http://www.cnblogs.com/feilong3540717/archive/2011/12/19/2293038.html)
其實這個hibernate.hbm2ddl.auto參數的作用主要用於:自動建立|更新|驗證資料庫表結構。如果不是此方面的需求建議set value="none"。
create:
每次載入hibernate時都會刪除上一次的產生的表,然後根據你的model類再重新來產生新表,哪怕兩次沒有任何改變也要這樣執行,這就是導致資料庫表資料丟失的一個重要原因。
create-drop :
每次載入hibernate時根據model類產生表,但是sessionFactory一關閉,表就自動刪除。
update:
最常用的屬性,第一次載入hibernate時根據model類會自動建立起表的結構(前提是先建立好資料庫),以後載入hibernate時根據 model類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到伺服器後,表結構是不會被馬上建立起來的,是要等 應用第一次運行起來後才會。
validate :
每次載入hibernate時,驗證建立資料庫表結構,只會和資料庫中的表進行比較,不會建立新表,但是會插入新值。
再說點“廢話”:
當我們把hibernate.hbm2ddl.auto=create時hibernate先用hbm2ddl來產生資料庫schema。
當我們把hibernate.cfg.xml檔案中hbm2ddl屬性注釋掉,這樣我們就取消了在啟動時用hbm2ddl來產生資料庫schema。通常 只有在不斷重複進行單元測試的時候才需要開啟它,但再次運行hbm2ddl會把你儲存的一切都刪除掉(drop)---- create配置的含義是:“在建立SessionFactory的時候,從scema中drop掉所以的表,再重新建立它們”。
注意,很多Hibernate新手在這一步會失敗,我們不時看到關於Table not found錯誤資訊的提問。但是,只要你根據上面描述的步驟來執行,就不會有這個問題,因為hbm2ddl會在第一次啟動並執行時候建立資料庫schema, 後續的應用程式重啟後還能繼續使用這個schema。假若你修改了映射,或者修改了資料庫schema,你必須把hbm2ddl重新開啟一次。
hibernate的current_session_context_class配置
情景1:
在使用SessionFactory的getCurrentSession方法時遇到如下錯誤,經過檢查,原因如下:
是因為在hibernate.cfg.xml檔案中忘記進行了如下設定:
hibernate.current_session_context_class如果是在web容器中運行hibernate,則在hibernate.cfg.xml中加入這句話:
<property name="hibernate.current_session_context_class">jta</property>
如果是在一個單獨的需要進行JDBC串連的Java application中運行hibernate,則這樣設定:
<property name="hibernate.current_session_context_class">thread</property>
解釋:
這裡getCurrentSession本地事務(本地事務:jdbc)時 要在設定檔裡進行如下設定
* 如果使用的是本地事務(jdbc事務)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全域事務(jta事務)
<property name="hibernate.current_session_context_class">jta</property>
hibernate設定檔