hibernate 自動生成數據庫表


只要在hibernate.cfg.xml添加這句話,就可以自動生成數據表
<property name="hibernate.hbm2ddl.auto">update</property>

update:表示自動根據model對象來更新表結構,啟動hibernate時會自動檢查數據庫,如果缺少表,則自動建表;如果表里缺少列,則自動添加列。

還有其他的參數:
create:啟動hibernate時,自動刪除原來的表,新建所有的表,所以每次啟動后的以前數據都會丟失。

create-drop:啟動hibernate時,自動創建表,程序關閉時,自動把相應的表都刪除。所以程序結束時,表和數據也不會再存在。

PS:數據庫要預先建立好,因為hibernate只會建表,不會建庫

 

==========================================

 

表結構和數據總是在程序執行的時候無端的修改,折騰了好長時間,查了很長時間hibernate的數據庫映射文件和接口程序,始終沒有發現有什么錯誤,到最后才發現了它!
           <property name="hibernate.hbm2ddl.auto" value="update" />
解釋如下:

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

其實這個參數的作用主要用於:自動創建|更新|驗證數據庫表結構。
如果沒有此方面的需求建議set value="none".

其它幾個參數的意思:

validate               加載hibernate時,驗證創建數據庫表結構
create                  每次加載hibernate,重新創建數據庫表結構
create-drop        加載hibernate時創建,退出是刪除表結構
update                 加載hibernate自動更新數據庫結構

如果發現數據庫表丟失或新增,請檢查hibernate.hbm2ddl.auto的配置 可設置 <property name="hibernate.hbm2ddl.auto" value="none" />

 
 
 
參考以上數據,我配置好了我的根據model生成數據庫表。具體如下
 
 
 
 
 
 
 
 
我有一個文件
hibernate.hbm2ddl.auto=update
 
 
 
另一個地方: 
 
 
 
 
   <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM