0


spring boot启动时自动创建数据库和表

自动创建数据库

spring boot 自带 如果数据库不存在,可以自动创建数据库

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

数据库连接加此参数即可,但是

数据库名称

,中间

不可以

-

字符(

横线

减号

),但

下划线可以

自动创建表

引用包

    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 设置库表对应实体

/**
 * 设备相关的所有日志
 *
 * @author Buter
 * @date 2020/3/15 18:05
 */@Data@Entity@Table(name ="test")publicclassTest/**
    * id
     **/@Id@GeneratedValue(strategy =GenerationType.IDENTITY)privateInteger id;/**
    * 名称
     **/privateString name;}

在启动时会自动 创建 表,如果表已经存在,但新增加的字段不存在那么,会自动创建字段,如果字段已经存在,那么什么也不改变。
所以,如果实体对应的字段 类型变了,需要手动去更改字段类型
此处受

spring.jpa.hibernate.ddl-auto

配置影响

自动执行初始化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: 删除表,重新创建schema
create-drop: 会话创建时创建schema,会话关闭时销毁schema

初始化时,如果

resources

目录下存在

schema.sql

文件和

data.sql

文件,那么会自动执行。
如果文件不存在则不执行。
使用最多时

data.sql

文件,自动生成一些定义好的数据


本文转载自: https://blog.csdn.net/wljk506/article/details/128657853
版权归原作者 风.foxwho 所有, 如有侵权,请联系我们删除。

“spring boot启动时自动创建数据库和表”的评论:

还没有评论