springdata jpa之ddl-auto配置的屬性

在jpa中ddl-auto一共有四種:spring

分別爲:sql

ddl-auto:create ----每次運行該程序,沒有表格會新建表格,表內有數據會清空;
ddl-auto:create-drop ----每次程序結束的時候會清空表
ddl-auto:update ---- 每次運行程序,沒有表格會新建表格,表內有數據不會清空,只會更新
ddl-auto: validate ---- 運行程序會校驗數據與數據庫的字段類型是否相同,不一樣會報錯。數據庫

 

 上圖爲properties配置文件的配置項:ui

使用1)spring.jpa.hibernate.ddl-auto=createspa

    運行的sql爲:  hibernate

Hibernate: drop table if exists auth_user Hibernate: create table auth_user (id bigint not null, account varchar(32), name varchar(32), pwd varchar(64), primary key (id)) engine=InnoDB Hibernate刪掉已經存在表, 並重建表,恐怖!!!

使用2)spring.jpa.hibernate.ddl-auto=create-dropcode

    運行的sql爲:blog

Hibernate: drop table if exists auth_user Hibernate: drop table if exists cardo Hibernate: create table auth_user (id bigint not null, account varchar(32), name varchar(32), pwd varchar(64), primary key (id)) engine=InnoDB Hibernate: create table cardo (id bigint not null, brand_id integer, brand_name varchar(16), primary key (id)) engine=InnoDB ... Hibernate: drop table if exists auth_user Hibernate: drop table if exists cardo

使用3)spring.jpa.hibernate.ddl-auto=update同步

    運行的sql爲:it

Hibernate: create table auth_user (id bigint not null, account varchar(32), name varchar(32), pwd varchar(64), primary key (id)) engine=InnoDB Hibernate: create table cardo (id bigint not null, brand_id integer, brand_name varchar(16), primary key (id)) engine=InnoDB

給entity類添加一個字段others, 表也會自動同步添加一個字段others.

@Entity @Table(name = "AUTH_USER") @Data @Builder @AllArgsConstructor @NoArgsConstructor public class UserDO { @Id private Long id; @Column(length = 32) private String name; @Column(length = 32) private String account; @Column(length = 64) private String pwd; @Column(length = 255) private String others; }

添加個字段others

    執行的sql爲:

Hibernate: alter table auth_user add column others varchar(255)

 

給表添加了字段others.

表添加一個字段, 對entity類有啥影響?
沒有任何影響.
Hibernate: insert into auth_user (account, name, others, pwd, id) values (?, ?, ?, ?, ?)

不會校驗entity中字段類型和表中對應的字段的類型是否匹配。

 

使用4)spring.jpa.hibernate.ddl-auto=validate

當表中字段others是varchar類型, 實體類entity的others是Integer類型,
類型不匹配報錯:

Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [others] in table [auth_user]; found [varchar (Types#VARCHAR)], but expecting [integer (Types#INTEGER)]

使用5)spring.jpa.hibernate.ddl-auto=none

禁止ddl

因爲ddl-auto不能同時指定多個屬性, 只能在create, create-drop, update, validate, none中選擇一個屬性

 

總結:
通常選擇validate/update/none
絕對不能選 create, create-drop

update能幫助建表。

若是但願實體類發生改動而數據庫表作出相應的更改且不破壞數據庫現有的數據,要將spring.jpa.hibernate.ddl-auto屬性值設置爲update

這裏還有一點,就算把ddl-auto設置成update值,也不能識別對錶結構的全部更改,每每只能識別出增長的字段,好比修改字段名,修改字段類型或者刪除一個字段都是不可以識別的。

相關文章
相關標籤/搜索