hibernate.hbm2ddl.auto配置及意义
***********************************************************
這兩天在整理Spring + JPA(Hibernate實現(xiàn)),從網(wǎng)上copy了一段Hibernate連接參數(shù)的配置。
<properties>
<property name="hibernate.show_sql" value="true" />??????
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
結果在測試時,老是發(fā)現(xiàn)數(shù)據(jù)庫表數(shù)據(jù)丟失。這個參數(shù)以前沒怎么用,查了一圈其它的東東,最后才定位到這個上面。趕緊查了一下Hibernate的參數(shù)配置,解釋如下:
hibernate.hbm2ddl.auto Automatically validate or export schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly. eg. validate | update | create | create-drop
其實這個參數(shù)的作用主要用于:自動創(chuàng)建|更新|驗證數(shù)據(jù)庫表結構。如果不是此方面的需求建議set value="none".
其它幾個參數(shù)的意思,我解釋一下:
validate ? ? ? ? ? ? ? ?加載hibernate時,驗證創(chuàng)建數(shù)據(jù)庫表結構
create????????????????? 每次加載hibernate,重新創(chuàng)建數(shù)據(jù)庫表結構,這就是導致數(shù)據(jù)庫表數(shù)據(jù)丟失的原因。
create-drop ? ? ? ? ?加載hibernate時創(chuàng)建,退出是刪除表結構
update???????????????? 加載hibernate自動更新數(shù)據(jù)庫結構
以上4個屬性對同一配置文件下所用有的映射表都起作用
?
總結:
1.請慎重使用此參數(shù),沒必要就不要隨便用。
2.如果發(fā)現(xiàn)數(shù)據(jù)庫表丟失,請檢查hibernate.hbm2ddl.auto的配置
***********************************************************
hibernate.hbm2ddl.auto
Hibernate Reference Documentation 3.3.1解釋如下:
Automatically validate or export schema DDL to the database when the SessionFactory is created.
With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.
eg. validate | update | create | create-drop
其實這個hibernate.hbm2ddl.auto參數(shù)的作用主要用于:
自動創(chuàng)建|更新|驗證數(shù)據(jù)庫表結構。
如果不是此方面的需求建議set value="none"。
create:
每次加載hibernate時都會刪除上一次的生成的表,然后根據(jù)你的model類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執(zhí)行,這就是導致數(shù)據(jù)庫表數(shù)據(jù)丟失的一個重要原因。
create-drop :
每次加載hibernate時根據(jù)model類生成表,但是sessionFactory一關閉,表就自動刪除。
update:
最常用的屬性,第一次加載hibernate時根據(jù)model類會自動建立起表的結構(前提是先建立好數(shù)據(jù)庫),以后加載hibernate時根據(jù) model類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到服務器后,表結構是不會被馬上建立起來的,是要等 應用第一次運行起來后才會。
validate :
每次加載hibernate時,驗證創(chuàng)建數(shù)據(jù)庫表結構,只會和數(shù)據(jù)庫中的表進行比較,不會創(chuàng)建新表,但是會插入新值。
再說點“廢話”:
當我們把hibernate.hbm2ddl.auto=create時hibernate先用hbm2ddl來生成數(shù)據(jù)庫schema。
當我們把hibernate.cfg.xml文件中hbm2ddl屬性注釋掉,這樣我們就取消了在啟動時用hbm2ddl來生成數(shù)據(jù)庫schema。通常 只有在不斷重復進行單元測試的時候才需要打開它,但再次運行hbm2ddl會把你保存的一切都刪除掉(drop)---- create配置的含義是:“在創(chuàng)建SessionFactory的時候,從scema中drop掉所以的表,再重新創(chuàng)建它們”。
注意,很多Hibernate新手在這一步會失敗,我們不時看到關于Table not found錯誤信息的提問。但是,只要你根據(jù)上面描述的步驟來執(zhí)行,就不會有這個問題,因為hbm2ddl會在第一次運行的時候創(chuàng)建數(shù)據(jù)庫schema, 后續(xù)的應用程序重啟后還能繼續(xù)使用這個schema。假若你修改了映射,或者修改了數(shù)據(jù)庫schema,你必須把hbm2ddl重新打開一次。
總結
以上是生活随笔為你收集整理的hibernate.hbm2ddl.auto配置及意义的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTML DOM节点的属性获取
- 下一篇: Faster RCNN详解