I'm using Spring Boot with JPA and 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. JPA manages the schema, database running MySQL and all the date columns are DateTime
. All Dates are of 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
.
Auditable.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:
Sample s = sampleRepository.getOne(id);
s.setApproved(new Date());
sampleRepository.save(s);
Spring Generates this error message:
com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'approved' at row 1
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).
Also, you can try @Temporal(TemporalType.DATE)
instead of TemporalType.TIMESTAMP
if you want to keep your code.
Sorry about I missed what exact subject you raised.
Just try add @Temporal(TemporalType.DATE)
above Date approved;
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.