配置hibernate根据实体类自动建表功能
Hibernate支持自動建表,在開發(fā)階段很方便,可以保證hbm與數(shù)據(jù)庫表結(jié)構(gòu)的自動同步。
如何使用呢?很簡單,只要在hibernate.cfg.xml里加上如下代碼
Xml代碼<property?name="hbm2ddl.auto">update</property>??
?
update:表示自動根據(jù)model對象來更新表結(jié)構(gòu),啟動hibernate時會自動檢查數(shù)據(jù)庫,如果缺少表,則自動建表;如果表里缺少列,則自動添加列。
還有其他的參數(shù):?
create:啟動hibernate時,自動刪除原來的表,新建所有的表,所以每次啟動后的以前數(shù)據(jù)都會丟失。
create-drop:啟動hibernate時,自動創(chuàng)建表,程序關(guān)閉時,自動把相應的表都刪除。所以程序結(jié)束時,表和數(shù)據(jù)也不會再存在。
PS:數(shù)據(jù)庫要預先建立好,因為hibernate只會建表,不會建庫
==========================================
表結(jié)構(gòu)和數(shù)據(jù)總是在程序執(zhí)行的時候無端的修改,折騰了好長時間,查了很長時間hibernate的數(shù)據(jù)庫映射文件和接口程序,始終沒有發(fā)現(xiàn)有什么錯誤,到最后才發(fā)現(xiàn)了它!
?????????? <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
其實這個參數(shù)的作用主要用于:自動創(chuàng)建|更新|驗證數(shù)據(jù)庫表結(jié)構(gòu)。
如果沒有此方面的需求建議set value="none".
其它幾個參數(shù)的意思:
validate?????????????? 加載hibernate時,驗證創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu)
create????????????????? 每次加載hibernate,重新創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu)
create-drop??????? 加載hibernate時創(chuàng)建,退出是刪除表結(jié)構(gòu)
update???????????????? 加載hibernate自動更新數(shù)據(jù)庫結(jié)構(gòu)
如果發(fā)現(xiàn)數(shù)據(jù)庫表丟失或新增,請檢查hibernate.hbm2ddl.auto的配置 可設(shè)置 <property name="hibernate.hbm2ddl.auto" value="none" />
建議在開發(fā)環(huán)境下使用,在生產(chǎn)環(huán)境下去掉。
?
優(yōu)點:
1、自動創(chuàng)建新表
2、自動創(chuàng)建新字段
3、自動修改字段類型
?
缺點:
1、不會自動刪除表
2、不會自動刪除字段
3、自動創(chuàng)建的新字段只能是在最后。
?
針對缺點的建議:定期把數(shù)據(jù)庫清空(刪除所有表),然后啟動項目,讓hibernate自動創(chuàng)建表結(jié)構(gòu)和索引,當然一些初始化數(shù)據(jù)需要手工導入。
轉(zhuǎn)載于:https://www.cnblogs.com/toSeeMyDream/p/5539360.html
總結(jié)
以上是生活随笔為你收集整理的配置hibernate根据实体类自动建表功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: ISLR—第二章 Statistical
- 下一篇: js字符串、数组和数字常用方法总结
