3.2章中按照書中的步驟寫好相應類的映射關係,發現啓動時,以前在3.1章中建的表所有被刪從新創建了,而且Ingredient
表的數據沒了,因爲使用了JPA,默認使用的是hibernate,在啓動時會刪除全部的表並從新的創建表結構,並且schema.sql
和data.sql
中的語句並無執行。解決辦法很簡單,在application.properties文件中加入下面的配置:java
spring.jpa.hibernate.ddl-auto=none
關閉掉hibernate的ddl的處理功能就能行了。spring
不過還有一些地方須要調整,在3.1章的表字段的命名是java風格的,在執行hibernate的查詢語句時會報錯,就拿Taco來講:sql
package tacos; import java.util.Date; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.PrePersist; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import lombok.Data; @Data @Entity public class Taco { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private Date createdAt; @NotNull @Size(min=5, message="Name must be at least 5 characters long") private String name; @ManyToMany(targetEntity=Ingredient.class) @Size(min=1, message="You must choose at least 1 ingredient") private List<Ingredient> ingredients; @PrePersist void createdAt() { this.createdAt = new Date(); } }
因爲createdAt屬性未加上@Column註解,那麼你會認爲它對應的字段會是createdAt,實際上再查詢時,你會發現他映射的字段是created_at,即便你給他加上@Column(name="createdAt")也不起做用,可是你給他加上@Column(name="createdat")確實能夠的。多是spring強制你的字段必須符合sql的字段命名標準,會自動將java的駝峯命名的熟悉名轉換成用下劃線分隔的形式。app
若是逐步的去按照@Column(name="createdat")這樣的方式去處理實在太麻煩了,因此直接修改了表結構的ddl語句,以下:ide
drop table Taco_Ingredients if exists; drop table Taco_Order_Tacos if exists; create table if not exists Ingredient ( id varchar(4) not null, name varchar(25) not null, type varchar(10) not null ); create table if not exists Taco ( id identity, name varchar(50) not null, created_at timestamp not null ); create table if not exists Taco_Ingredients ( taco_id bigint not null, ingredients_id varchar(4) not null ); alter table Taco_Ingredients add foreign key (taco_id) references Taco(id); alter table Taco_Ingredients add foreign key (ingredients_id) references Ingredient(id); create table if not exists Taco_Order ( id identity, delivery_name varchar(50) not null, delivery_street varchar(50) not null, delivery_city varchar(50) not null, delivery_state varchar(2) not null, delivery_zip varchar(10) not null, cc_number varchar(16) not null, cc_expiration varchar(5) not null, ccCVV varchar(3) not null, placed_at timestamp not null ); create table if not exists Taco_Order_Tacos ( order_id bigint not null, taco_id bigint not null ); alter table Taco_Order_Tacos add foreign key (order_id) references Taco_Order(id); alter table Taco_Order_Tacos add foreign key (taco_id) references Taco(id);
把上面的語句放入schema.sql文件就能完美解決問題。this