【spring实战第五版遇到的坑】3.2中配置关系映射时,表名和3.1中不同

3.2章中按照书中的步骤写好相应类的映射关系,发现启动时,以前在3.1章中建的表所有被删从新创建了,而且Ingredient表的数据没了,因为使用了JPA,默认使用的是hibernate,在启动时会删除全部的表并从新的创建表结构,并且schema.sqldata.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

相关文章
相关标签/搜索