在Java中,日期类型总是返回1970-01-01作为默认值

5uzkadbs  于 2023-10-14  发布在  Java
关注(0)|答案(1)|浏览(123)

setDOB方法总是在数据库中插入1970-01-01。
无法更改java. util中的日期的DOB的dataTypeJSON Postman 请求是这样接收的:

{
"DOB":"20101123"
}

请求将只以这种格式接收,并且它应该插入到像2010-11-23这样的数据库中
但只有1970-01-01在每次请求时插入数据库。

ServiceClass方法

private void updateExistingEmployee(OrgEmployeeMap existingOrgEmployee, RequestMessage requestMessage) {
    try {
        EmployeeInformation employeeInfo = requestMessage.getEmployeeInformation();
        final var updater = new Updater(existingOrgEmployee, employeeInfo);

        updater
            .update("DOB", EmployeeInformation::getDOB, OrgEmployeeMap::getDob, OrgEmployeeMap::setDob)
            .update("Email", EmployeeInformation::getEmail, OrgEmployeeMap::getEmail, OrgEmployeeMap::setEmail);

    
        orgEmployeeMapRepository.save(existingOrgEmployee);

        log.info("Updated Employee : " + existingOrgEmployee);
    } catch (JSONException e) {
        log.error("error in processing the request error", e.getMessage());
    } 
}

public static class Updater {
  private final OrgEmployeeMap existing;
  private final EmployeeInformation information;
  private final Set<String> updatedFields = new HashSet<>();

  public Updater(OrgEmployeeMap existing, EmployeeInformation information) {
    this.existing = existing;
    this.information = information;
  }

  public <T> Updater update(String fieldName,
                            Function<EmployeeInformation, T> newValueGetter,
                            Function<OrgEmployeeMap, T> oldValueGetter,
                            BiConsumer<OrgEmployeeMap, T> oldValueSetter) {
    final var newValue = newValueGetter.apply(information);
    final var oldValue = oldValueGetter.apply(existing);
    if (newValue == null || newValue.equals(oldValue)) {
      return this;
    }
    this.updatedFields.add(fieldName);
    oldValueSetter.accept(existing, newValue);
    return this;
  }

  public Set<String> getUpdatedFields() {
    return updatedFields;
  }
}

DTO类

@Data
public class EmployeeInformation {

    @JsonProperty(value = "Email")
    private String Email;

    @JsonProperty(value = "EmployeeFirstName")
    private String EmployeeFirstName;

    @JsonProperty(value = "EmployeeLastName")
    private String EmployeeLastName;

    @JsonProperty(value = "DOB")
    private Date DOB;

..
}

模型类

@Data
@Entity
@Table(name = "employee")
public class EmployeeMap {
@Id
    @Column(name = "Id", length = 100, nullable = false)
    private String Id;

    @Column(name = "firstName", length = 100, nullable = false)
    private String firstName;

    @Column(name = "lastName", length = 100)
    private String lastName;

    @Column(name = "email", length = 100, nullable = false)
    private String email;

    @Column(name = "dob", nullable = false)
    private Date dob;
}
7eumitmz

7eumitmz1#

这个有用吗?

@JsonProperty(value = "DOB")
@JsonFormat(pattern = "yyyyMMdd", shape = JsonFormat.Shape.STRING)
private Date DOB;

相关问题