我刚刚更改了一个表place
,它的列claimed
像这样:
ALTER TABLE place
ADD COLUMN IF NOT EXISTS claimed boolean NOT NULL DEFAULT false;
在phpPgAdmin中,我看到它有效。同样,所有初始值都正确设置为false
。
但是,当我创建新记录时:
this.placeRepository.save(place);
我得到:
ERROR: null value in column "claimed" violates not-null constraint
或整体上:
2018-09-21 21:56:47.902 WARN 30087 --- [nio-8443-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2018-09-21 21:56:47.903 ERROR 30087 --- [nio-8443-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: null value in column "claimed" violates not-null constraint
Detail: Failing row contains (17, 2018-09-21 19:56:47.885, 2018-09-21 19:56:47.885, ChIJj15CRtukokcRcvSmyJCKGU4, 49.7759560000000008, 9.57715980000000044, Wertheim Village, Almosenberg, Wertheim, null).
2018-09-21 21:56:47.908 INFO 30087 --- [nio-8443-exec-9] m.a.s.e.CustomRestExceptionHandler : org.springframework.dao.DataIntegrityViolationException
2018-09-21 21:56:47.908 INFO 30087 --- [nio-8443-exec-9] m.a.s.e.CustomRestExceptionHandler : org.hibernate.exception.ConstraintViolationException
我看不出这里有什么问题。那么为什么这里没有生成默认值呢?在我看来,Hibernate只是尝试插入一个null
值?
我认为这无关紧要,只是为了确保我还在自己的Java代码中将nullable = false
添加到了实体类的列:
@Column(nullable = false)
private Boolean claimed;
答案 0 :(得分:1)
解决方案是:
只需为字段设置默认值
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css"
integrity="sha384-EkHEUZ6lErauT712zSr0DZ2uuCmi3DoQj6ecNdHQXpMpFNGAQ48WjfXCE5n20W+R"
crossorigin="anonymous"
asp-fallback-href="~/lib/dist/css/dataTables.bootstrap4.min.css"
asp-fallback-test-class=".dataTable"
asp-fallback-test-property="clear"
asp-fallback-test-value="both" />
如果未设置默认值,请设置默认值
@Column(nullable = false)
private Boolean claimed = true;
使用columnDefinition
@PrePersist
public void prePersist() {
if(claimed == null)
claimed = true;
}