springdata jpa之ddl-auto配置的屬性


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

分別為:

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

 

 上圖為properties配置文件的配置項:

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

    運行的sql為:  

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-drop

    運行的sql為:

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為:

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值,也不能識別對表結構的所有更改,往往只能識別出增加的字段,比如修改字段名,修改字段類型或者刪除一個字段都是不能夠識別的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM