2. ddl-auto
ddl-auto
自己手動(dòng)測試下唄
1)spring.jpa.hibernate.ddl-auto=create
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刪掉已經(jīng)存在表, 并重建表,恐怖!!处嫌!
- spring.jpa.hibernate.ddl-auto=create-drop
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
- spring.jpa.hibernate.ddl-auto=update
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類添加一個(gè)字段others, 表也會(huì)自動(dòng)同步添加一個(gè)字段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;
}
添加個(gè)字段others
Hibernate: alter table auth_user add column others varchar(255)
給表添加了字段others.
表添加一個(gè)字段, 對(duì)entity類有啥影響?
沒有任何影響.
Hibernate: insert into auth_user (account, name, others, pwd, id) values (?, ?, ?, ?, ?)
不會(huì)校驗(yàn)entity中字段類型和表中對(duì)應(yīng)的字段的類型是否匹配斩个。
- spring.jpa.hibernate.ddl-auto=validate
當(dāng)表中字段others是varchar類型, 實(shí)體類entity的others是Integer類型驯杜,
類型不匹配報(bào)錯(cuò):
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)]
- spring.jpa.hibernate.ddl-auto=none
禁止ddl
- ddl-auto不能同時(shí)指定多個(gè)屬性受啥, 只能在create, create-drop, update, validate, none中選擇一個(gè)屬性
- 總結(jié):
一般選擇validate/update/none
絕對(duì)不能選 create, create-drop
update能幫助建表。
如果希望實(shí)體類發(fā)生改動(dòng)而數(shù)據(jù)庫表做出相應(yīng)的更改且不破壞數(shù)據(jù)庫現(xiàn)有的數(shù)據(jù)鸽心,要將spring.jpa.hibernate.ddl-auto屬性值設(shè)置為update
這里還有一點(diǎn)滚局,就算把ddl-auto設(shè)置成update值,也不能識(shí)別對(duì)表結(jié)構(gòu)的所有更改顽频,往往只能識(shí)別出增加的字段藤肢,比如修改字段名,修改字段類型或者刪除一個(gè)字段都是不能夠識(shí)別的糯景。
ddl-auto:create ----每次運(yùn)行該程序嘁圈,沒有表格會(huì)新建表格省骂,表內(nèi)有數(shù)據(jù)會(huì)清空;
ddl-auto:create-drop ----每次程序結(jié)束的時(shí)候會(huì)清空表
ddl-auto:update ---- 每次運(yùn)行程序最住,沒有表格會(huì)新建表格钞澳,表內(nèi)有數(shù)據(jù)不會(huì)清空,只會(huì)更新
ddl-auto: validate ---- 運(yùn)行程序會(huì)校驗(yàn)數(shù)據(jù)與數(shù)據(jù)庫的字段類型是否相同涨缚,不同會(huì)報(bào)錯(cuò)轧粟。