问题描述
我正在使用Java 1.8和SpringBoot 2.3.4.RELEASE。我正在尝试使用AuditingEntityListener和@MappedSuperclass功能来填充created_date和Updated_date时间戳。
但是我遇到了这个异常: java.lang.classCastException:无法将java.lang.String转换为java.time.LocalDateTime
我尝试了没有@MappedSuperclass的情况,它可以工作.....但是未填充created_date和updated_date字段。
有人可以帮我吗?
这是代码段:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class AuditableEntity implements Serializable {
@CreatedDate
@Column(name = "created_ts",nullable = false,updatable = false)
private LocalDateTime createdDate;
@LastModifiedBy
@Column(name = "updated_ts",nullable = false)
private LocalDateTime updatedDate;
@CreatedBy
@Column(name = "src_sys_cd",length = 15,updatable = false)
private String source;
@Version
@Column(name = "record_version_nb",length = 20,nullable = false)
private Long version;
}
----------------------------------
@Component
public class AuditorAwareImpl implements AuditorAware<String> {
@Value("${customer.service.source.code}")
private String auditor;
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of(auditor);
}
}
----------------------------------
@Entity
@Setter
@Getter
@Builder
@Table(name = "customer_information")
@AllArgsConstructor
@NoArgsConstructor
public class CustomerEntity extends AuditableEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
}
解决方法
@LastModifiedBy
用于在修改发生时设置当前用户。通常是String
,它不能转换为任何日期/时间,而且似乎也不是您想要的。
您应该将其更改为:
@LastModifiedBy
@Column(name = "updated_ts",nullable = false)
private LocalDateTime updatedDate;
@LastModifiedDate
@Column(name = "updated_ts",nullable = false)
private LocalDateTime updatedDate;