欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot啟動同時創(chuàng)建數據庫和表實現(xiàn)方法

 更新時間:2023年01月14日 11:10:13   作者:風.foxwho  
這篇文章主要介紹了Springboot啟動同時創(chuàng)建數據庫和表,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧

自動創(chuàng)建數據庫

spring boot 自帶 如果數據庫不存在,可以自動創(chuàng)建數據庫

spring.datasource.url=jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=true&characterEncoding=utf8mb4&useSSL=false&allowPublicKeyRetrieval=true

createDatabaseIfNotExist=true 數據庫連接加此參數即可,但是數據庫名稱,中間不可以有 - 字符(橫線 或 減號),但 下劃線可以

自動創(chuàng)建表

引用包

    api('org.springframework.boot:spring-boot-starter-web:2.6.2')
    api('org.springframework.boot:spring-boot-starter-data-jpa:2.6.2')
    implementation('mysql:mysql-connector-java:8.0.27')

使用 JPA 設置庫表對應實體

/**
 * 設備相關的所有日志
 */
@Data
@Entity
@Table(name = "test")
public class Test
     /**
    * id
     **/
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
    /**
    * 名稱
     **/
	private String name;
}

在啟動時會自動 創(chuàng)建 表,如果表已經存在,但新增加的字段不存在那么,會自動創(chuàng)建字段,如果字段已經存在,那么什么也不改變。

所以,如果實體對應的字段 類型變了,需要手動去更改字段類型

此處受spring.jpa.hibernate.ddl-auto配置影響

自動執(zhí)行初始化sql 文件

配置如下

spring.sql.init.mode=always
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

ddl-auto 枚舉:
none(默認):禁用DDL處理
validate:驗證schema,不做任何操作
update: 更新schema
create: 刪除表,重新創(chuàng)建schema
create-drop: 會話創(chuàng)建時創(chuàng)建schema,會話關閉時銷毀schema

初始化時,如果 resources目錄下存在 schema.sql文件和data.sql文件,那么會自動執(zhí)行。

如果文件不存在則不執(zhí)行。

使用最多時data.sql文件,自動生成一些定義好的數據

到此這篇關于Springboot啟動同時創(chuàng)建數據庫和表實現(xiàn)方法的文章就介紹到這了,更多相關Springboot創(chuàng)建數據庫內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論