【问题标题】:Hibernate and MySQL: @CreationTimestamp annotated Date property throws ConstraintViolationException when saving new EntityHibernate 和 MySQL:@CreationTimestamp 注释的 Date 属性在保存新实体时抛出 ConstraintViolationException
【发布时间】:2020-03-24 11:30:59
【问题描述】:

我正在使用 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 类:

@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
}

堆栈跟踪:

2019 年 11 月 28 日晚上 9:07:28 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions 警告:SQL 错误:1048,SQLState:23000 2019 年 11 月 28 日晚上 9:07:28 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions 错误:列 'tstamp' 不能为空 2019 年 11 月 28 日晚上 9:07:28 org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure 错误:HHH000346:托管刷新期间出错 [org.hibernate.exception.ConstraintViolationException:无法执行语句] 2019 年 11 月 28 日晚上 9:07:28 org.apache.catalina.core.StandardWrapperValve 调用 严重:servlet [dispatcher] 在路径 [/tms-rest-again] 的上下文中的 Servlet.service() 引发异常 [请求处理失败;嵌套异常是 org.springframework.dao.DataIntegrityViolationException:无法执行语句; SQL [不适用];约束 [null];嵌套异常是 org.hibernate.exception.ConstraintViolationException: could not execute statement] 根本原因 java.sql.SQLIntegrityConstraintViolationException:列 'tstamp' 不能为空 在 com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)

【问题讨论】:

  • 什么是休眠版本,两个场景会出现同样的错误吗?
  • 如果使用第二个发布请求出现错误,请尝试使用@Column(name= "tstamp", nullable = false, updatable = false)
  • @monster 休眠版本是 5.1.0,我在两种情况下都得到了相同的堆栈跟踪。不幸的是,将您的建议添加到代码中并没有解决问题。

标签: java mysql spring hibernate


【解决方案1】:

我删除了@CreationTimestamp 并这样写:

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

提示this 回答。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    相关资源
    最近更新 更多