bha*_*avs 7 java hibernate spring-boot
一段时间以来,我一直在尝试修改我的架构;通过更改 SpringBoot 中的模型定义。
我还有 commndLineRunner,它将用一些示例数据填充表。由于某种原因,我无法将列添加到现有表中。
我确实执行了一个 alter table 命令,这在大多数情况下都是不合理和不实用的;(这解决了一次问题;但我不想再诉诸于此)。
我感觉这与 SpringBoot MicroService 中 JPA 属性的定义有更多关系。这看起来像这样:
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.hikari.maximum-pool-size=30
spring.jpa.show-sql = true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
Run Code Online (Sandbox Code Playgroud)
这是我执行 SpringBoot 应用程序时看到的错误:
Hibernate: alter table if exists public.package_definition add column no_of_email_review_requests int4 not null
Error executing DDL "alter table if exists public.package_definition add column no_of_email_review_requests int4 not null" via JDBC Statement
Caused by: org.postgresql.util.PSQLException: ERROR: column "no_of_email_review_requests" contains null values
Run Code Online (Sandbox Code Playgroud)
这是我尝试添加到我的实体中的附加列:
private int noOfEmailReviewRequests;
Run Code Online (Sandbox Code Playgroud)
编辑共享实体类:
@Entity
@Data
public class PackageDefinition {
@Id
private String id;
private SubscriptionType type;
private int noOfSMSReviewRequests;
private int noOfFunnelPages;
private Integer noOfEmailReviewRequests;
}
Run Code Online (Sandbox Code Playgroud)
编辑 :
这里似乎有两个问题,但都对应于同一个表和列添加/修改。我已重命名表中的以下列已重命名:
no_review_requests to no_of_sms_review_requests --> this is throwing an error
Run Code Online (Sandbox Code Playgroud)
并且添加了以下列:
private Integer noOfEmailReviewRequests;
Run Code Online (Sandbox Code Playgroud)
您必须为现有行设置非空列的默认值。
为此,请使用列定义
@Column(columnDefinition="COLUMN_TYPE default '0'")
Run Code Online (Sandbox Code Playgroud)
其中COLUMN_TYPE是您选择的列的 SQL 类型。
或(依赖于 Hibernate)
@ColumnDefault(0)
Run Code Online (Sandbox Code Playgroud)
https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/annotations/ColumnDefault.html
@NotNull在默认配置下,如果此表中有任何数据,则无法添加带注释的新列。
有2种解决方案:
spring.jpa.properties.hibernate.validator.apply_to_ddl=false到您的 application.properties。@NotNull注释的情况下运行。之后,@NotNull向您的实体添加注释。我不确定第二个选项,但第一个选项是完全有效的解决方案。
编辑:您还可以使用默认值定义新列,例如@Column(columnDefinition = "int default 100")。
| 归档时间: |
|
| 查看次数: |
14955 次 |
| 最近记录: |