gpt4 book ai didi

java - Hibernate 和 MySQL : @CreationTimestamp annotated Date property throws ConstraintViolationException when saving new Entity

转载 作者:行者123 更新时间:2023-11-29 15:25:55 24 4
gpt4 key购买 nike

我正在使用 Hibernate 和 MySQL 制作 Spring MVC 应用程序。我的一个 MySQL 表中有一个 TIMESTAMP 列,其定义如下 tstamp timestamp default current_timestamp。该表的实体有一个复合主键,其中包括 tstamp 列。

我定义EmbeddedId的实体类部分:

@Entity
@Table(name="trustassessments")
public class TrustAssessment {

@EmbeddedId
@JsonView(Views.Public.class)
private TrustAssessmentId id;
....

我定义时间戳的可嵌入类:

@Embeddable
public class TrustAssessmentId implements Serializable {

@Column(name="deviceId")
int deviceId;

@Column(name="tmsId")
int tmsId;

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name="tstamp")
private Date tstamp;
....

我正在使用 Jackson,所以我以 json 格式发布,并且我尝试了这两个:

1.

{
"id": {
"deviceId": 21,
"tmsId": "20"
},
"trustLevel": 0.4,
"honesty": 0.6,
"cooperativeness": 0.4,
"communityInterest": 0.2
}

2.

{
"id": {
"deviceId": 21,
"tmsId": "20",
"tstamp": ""
},
"trustLevel": 0.4,
"honesty": 0.6,
"cooperativeness": 0.4,
"communityInterest": 0.2
}

堆栈跟踪:

Nov 28, 2019 9:07:28 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN: SQL Error: 1048, SQLState: 23000 Nov 28, 2019 9:07:28 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR: Column 'tstamp' cannot be null Nov 28, 2019 9:07:28 PM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure ERROR: HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement] Nov 28, 2019 9:07:28 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/tms-rest-again] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause java.sql.SQLIntegrityConstraintViolationException: Column 'tstamp' cannot be null at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)

最佳答案

我删除了@CreationTimestamp并这样写:

@Column(name="tstamp", updatable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date tstamp = new Date();

支持this回答。

但是,如果有人能解释它是如何工作的以及为什么它不能与 @CreationTimestamp 一起工作,那就太好了。

关于java - Hibernate 和 MySQL : @CreationTimestamp annotated Date property throws ConstraintViolationException when saving new Entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59095108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com