【发布时间】:2020-03-12 19:27:02
【问题描述】:
我有一个模型,例如:
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Map;
@Entity
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@Getter
public class MyTable {
@Id
long myId;
@NotNull
String myField_1;
@ElementCollection(fetch = FetchType.EAGER)
@NonNull
Map<Integer, BigDecimal> myField_2;
}
我在服务器上运行它,应用程序(一个 Spring Boot 应用程序)使用这个表一段时间,我决定我需要另一个字段:
@ElementCollection(fetch = FetchType.EAGER)
@NonNull
Map<Integer, BigDecimal> myAdditionalField;
但是当我再次在服务器上运行应用程序时,我得到了这样的异常:
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table my_table_my_additional_field add constraint FK35gbk1v4oaclmxu6onjiopln0 foreign key (my_table_my_id) references my_table (my_id)" via JDBC Statement
...
Caused by: java.sql.SQLException: Can't create table `my_database_name`.`#sql-7f7_4531` (errno: 150 "Foreign key constraint is incorrectly formed")
为什么会发生这种情况以及如何向我的实体添加新字段?我有一个属性jpa.hibernate.ddl-auto: update。最有趣的部分是该字段及其“地图集合”已正确添加到数据库中,只是这个新字段存在这个奇怪的约束错误
【问题讨论】:
-
要以更可预测的方式更新表,请考虑使用 Flyway (rieckpil.de/…)。使用 Flyway,您可以完全控制架构迁移,就像使用
jpa.hibernate.ddl-auto: update一样,您将控制权交给了 Hibernate,这可能会做一些您不打算做的事情。
标签: java mysql spring jpa mariadb