【问题标题】:Request processing failed; nested exception is java.lang.ClassCastException: Cannot cast java.lang.String to java.time.LocalDateTime] with root cause请求处理失败;嵌套异常是 java.lang.ClassCastException: Cannot cast java.lang.String to java.time.LocalDateTime] 根本原因
【发布时间】:2020-11-10 21:11:17
【问题描述】:

我正在使用 Java 1.8 和 SpringBoot 2.3.4.RELEASE。我正在尝试使用 AuditingEntityListener 和 @MappedSuperclass 功能来填充 created_date 和 updated_date 时间戳。

但是我得到了这个异常:java.lang.ClassCastException: Cannot cast java.lang.String to java.time.LocalDateTime

我尝试不使用 @MappedSuperclass 并且它可以工作.....但是 created_date 和 updated_date 字段没有被填充。

谁能帮我解决这个问题?

这里是sn-p的代码:

@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 private LocalDateTime updatedDate有关?我想你的意思是@LastModifiedDate
  • 是的,你是对的......我的意思是@LastModifiedDate......我错过了。感谢识别。欣赏它。

标签: spring spring-boot hibernate java-8 spring-data-jpa


【解决方案1】:

@LastModifiedBy 用于在发生修改时设置当前用户。这通常是 String,它不能转换为任何日期/时间,而且似乎不是您要找的。 您应该将其更改为:

@LastModifiedBy
@Column(name = "updated_ts",nullable = false)
private LocalDateTime updatedDate;


@LastModifiedDate
@Column(name = "updated_ts",nullable = false)
private LocalDateTime updatedDate;

【讨论】:

  • 非常感谢您的识别……我看了很多遍,以为我保留了@LastModifiedDate……所以没注意到。 :)
猜你喜欢
  • 2021-01-17
  • 1970-01-01
  • 2021-10-06
  • 2018-05-11
  • 2013-05-06
  • 2021-12-21
  • 2020-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多