3.2章中按照书中的步骤写好相应类的映射关系,发现启动时,之前在3.1章中建的表全部被删重新建立了,并且Ingredient
表的数据没了,由于使用了JPA,默认使用的是hibernate,在启动时会删除所有的表并重新的建立表结构,而且schema.sql
和data.sql
中的语句并没有执行。解决办法很简单,在application.properties文件中加入下面的配置:
spring.jpa.hibernate.ddl-auto=none
关闭掉hibernate的ddl的处理功能就能行了。
不过还有一些地方需要调整,在3.1章的表字段的命名是java风格的,在执行hibernate的查询语句时会报错,就拿Taco来说:
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 ingredients;
@PrePersist
void createdAt() {
this.createdAt = new Date();
}
}
由于createdAt属性未加上@Column注解,那么你会认为它对应的字段会是createdAt,实际上再查询时,你会发现他映射的字段是created_at,即使你给他加上@Column(name="createdAt")也不起作用,但是你给他加上@Column(name="createdat")确实可以的。可能是spring强制你的字段必须符合sql的字段命名标准,会自动将java的驼峰命名的熟悉名转换成用下划线分隔的形式。
如果逐步的去按照@Column(name="createdat")这样的方式去处理实在太麻烦了,所以直接修改了表结构的ddl语句,如下:
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文件就能完美解决问题。