简体   繁体   English

设置日期时无法保存实体

[英]Unable to save entity when date is set

I'm using Spring Boot with JPA and Lombok.我正在使用 Spring 引导与 JPA 和 Lombok。 My Sample entity contains four dates, the approved date, sample date, and a createdAt and modifiedAt that is maintained by JPA itself with the Auditable class. My Sample实体包含四个日期,即批准日期、样品日期和createdAtmodifiedAt ,由 JPA 本身和可审计的Auditable维护。 JPA manages the schema, database running MySQL and all the date columns are DateTime . JPA 管理模式,数据库运行 MySQL 并且所有日期列都是DateTime All Dates are of class java.util.Date .所有日期均为 class java.util.Date

Sample entity (simplified for reasons)示例实体(出于某种原因进行了简化)

@Entity
@Data
@EqualsAndHashCode(callSuper = false)
public class Sample extends Auditable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Integer id;

    Date approved;

    @DateTimeFormat(pattern = "yyyy-MM-dd'T'H:m")
    Date sampleDate;
}

The DateTimeFormat on the sampleDate is to help Spring convert form-data to a java.util.Date . sampleDate上的DateTimeFormat是为了帮助 Spring 将表单数据转换为java.util.Date

Auditable.java可审计的.java

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class Auditable {

    @CreatedDate
    @Column(name = "created_at", updatable = false, nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;

    @LastModifiedDate
    @Column(name = "modified_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date modifiedAt;
}

When my controller performs this:当我的 controller 执行此操作时:

Sample s = sampleRepository.getOne(id);
s.setApproved(new Date());
sampleRepository.save(s);

Spring Generates this error message: Spring 生成此错误消息:

com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'approved' at row 1 com.mysql.cj.jdbc.exceptions.MysqlDataTruncation:数据截断:行“已批准”列的数据太长

You would better use LocalDateTime instead of java.util.Date or java.sql.Date , if you are doing this with java >= 8. You would better use LocalDateTime instead of java.util.Date or java.sql.Date , if you are doing this with java >= 8.

Audited entities' createdDate, lastModifiedDate should be set by Jpa Auditor(framework), not by client(in this context, you).被审计实体的 createdDate、lastModifiedDate 应该由 Jpa Auditor(框架)设置,而不是由客户(在这种情况下,你)设置。

Also, you can try @Temporal(TemporalType.DATE) instead of TemporalType.TIMESTAMP if you want to keep your code.此外,如果您想保留代码,可以尝试@Temporal(TemporalType.DATE)而不是TemporalType.TIMESTAMP

Updated更新

Sorry about I missed what exact subject you raised.抱歉,我错过了您提出的确切主题。

Just try add @Temporal(TemporalType.DATE) above Date approved;只需尝试在批准日期上方添加@Temporal(TemporalType.DATE) Date approved; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM