Springboot 之 Hibernate自动建表(Mysql)
前些天發(fā)現(xiàn)了一個巨牛的人工智能學習網(wǎng)站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉(zhuǎn)到教程。
?
- 引入Maven依賴包
spring-boot-starter-data-jpa中已經(jīng)包含了Hibernate所需要的相關依賴,所以只需要引入Jpa的依賴即可。
- 創(chuàng)建配置文件
在application.properties中加一行:spring.profiles.active=dev
application-dev.properties配置文件的內(nèi)容如下:
server.port=80# Hibernate 相關配置## 方言 #hibernate.dialect=org.hibernate.dialect.MySQL5Dialect ## 顯示Sql hibernate.show_sql=true ## 自動建表方式 #hibernate.hbm2ddl.auto= update ## 自動掃描的包前綴 entitymanager.packagesToScan= com.zslin## 數(shù)據(jù)庫連接 spring.datasource.url=jdbc:mysql://localhost:3306/study05?\useUnicode=true&characterEncoding=utf-8&useSSL=true&autoReconnect=true## 用戶名 spring.datasource.username=root## 密碼 spring.datasource.password=123## 數(shù)據(jù)庫驅(qū)動 spring.datasource.driver-class-name=com.mysql.jdbc.Driver## 建表方式 spring.jpa.properties.hibernate.hbm2ddl.auto=update# 方言 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect注意:最關鍵的是最后兩個配置,spring.jpa.properties.hibernate.hbm2ddl.auto=update而不是hibernate.hbm2ddl.auto=update,使用了Jpa所以鍵名稱需要有相應調(diào)整,否則不會自動建表
spring.jpa.properties.hibernate.hbm2ddl.auto有幾種配置:
-
create:每次加載Hibernate時都會刪除上一次生成的表,然后重新生成新表,即使兩次沒有任何修改也會這樣執(zhí)行,這就導致每次啟動都是一個新的數(shù)據(jù)庫,也是導致數(shù)據(jù)丟失的重要原因。
-
create-drop:每次加載Hibernate時都會生成表,但當SessionFactory關閉時,所生成的表將自動刪除。
-
update:最常用的屬性值,第一次加載Hibernate時創(chuàng)建數(shù)據(jù)表(前提是需要先有數(shù)據(jù)庫),以后加載HIbernate時只會根據(jù)model更新,即使model已經(jīng)刪除了某些屬性,數(shù)據(jù)表也不會隨之刪除字段。
-
validate:每次加載Hibernate時都會驗證數(shù)據(jù)表結構,只會和已經(jīng)存在的數(shù)據(jù)表進行比較,根據(jù)model修改表結構,但不會創(chuàng)建新表。
具體配置可參考文章《Springboot 之 文件結構和配置文件》
- 創(chuàng)建Model實體類
注意:
1、 在主建Id上需要加注釋:@Id和@GeneratedValue(strategy = GenerationType.AUTO)才會自動增長
2、 在需要重新設置表字段名的屬性上加注釋@Column(name = "字段名")即可。
3、 在類名上添加注釋:@Entity和@Table(name = "t_user"),t_user是表名
- 啟動項目
啟動項目后在study05數(shù)據(jù)庫中將出現(xiàn)t_user的數(shù)據(jù)表,且存在相應的表字段。
示例代碼:https://github.com/zsl131/spring-boot-test/tree/master/study05
?
總結
以上是生活随笔為你收集整理的Springboot 之 Hibernate自动建表(Mysql)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SharePoint2010内容类型剖析
- 下一篇: 数据库经典DB2在技术前沿展现王者风范