我正在使用Spring. jpa.hibernate.ddl-auto=update属性来更新架构。
根据我的理解,如果我们对实体进行更改,那么表模式就会更新。
但是在Spring启动应用程序启动时,每次为外键执行更改命令。
以下是实体。
@Entity
@Table(name = "feedback")
@Data
public class Feedback implements Serializable {
private static final long serialVersionUID = -6420805626682233375L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "study_id")
@JsonIgnore
private Study study;
@ManyToOne(fetch= FetchType.EAGER)
@JoinColumn(name="user_id", nullable = false)
private User user;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "feedback_date", nullable = false)
private Date feedbackDate;
@Size(max = 1000)
@Column(name = "feedback", length = 1000)
private String feedback;
}
在实体中,您可以看到我有以下两个属性,用于在Spring启动应用程序首次启动时创建外键:
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "study_id")
@JsonIgnore
private Study study;
@ManyToOne(fetch= FetchType.EAGER)
@JoinColumn(name="user_id", nullable = false)
private User user;
因此,当我每次重新启动应用程序或保存代码时,外键约束都会被更改,即使我没有更改该关系(属性)。
2018-12-05 18:44:12.027 INFO 22736 --- [ restartedMain] c.d.smartviewer.SmartViewerApplication : Starting SmartViewerApplication on LAPTOP-F95LLCU3 with PID 22736 (D:\Sagar_\SVN\SmartViewer\target\classes started by ASUS in D:\Sagar_\SVN\SmartViewer)
2018-12-05 18:44:12.027 DEBUG 22736 --- [ restartedMain] c.d.smartviewer.SmartViewerApplication : Running with Spring Boot v2.0.6.RELEASE, Spring v5.0.10.RELEASE
2018-12-05 18:44:12.027 INFO 22736 --- [ restartedMain] c.d.smartviewer.SmartViewerApplication : No active profile set, falling back to default profiles: default
2018-12-05 18:44:13.356 INFO 22736 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1329 ms
Hibernate: alter table annotation add constraint FK7hwy1g5myfk7grmm2j7faqggd foreign key (parent_id) references annotation (id)
Hibernate: alter table feedback add constraint FKfxt8nk3jikofi3x40bsjd00vt foreign key (study_id) references study (id)
Hibernate: alter table feedback add constraint FK7k33yw505d347mw3avr93akao foreign key (user_id) references user (id)
Hibernate: alter table hospital add constraint FK3922fhj7qnyc3bw5x8xl6m6xc foreign key (contact_1) references contact (id)
那么,如果我不改变外键实体属性,我应该改变什么来不执行外键的改变命令呢?
约束是数据库模式定义的一部分。约束是在表的数据列上强制执行的规则。这些规则用于限制可以进入表的数据类型。这确保了数据库中数据的准确性和可靠性。约束可以是列级别的,也可以是表级别的。列级别的约束仅应用于一列,而表级别的约束应用于整个表。
约束的种类有:
问:Hibernate中的这个约束是可选的还是取消更新?
答:不,它不是可选的,它是关系实体所需要的。
如有必要,您还可以在运行时更改的DB中定义此约束,但请注意不要推荐。
我认为这是hibernate基于以下链接每次更改的bug(相同的问题):
https://discourse.hibernate.org/t/manytoone-alter-table-query-is-generating-every-time-when-inserting-a-value/1162/6