使用LocalDate从数据库实体检索

时间:2018-03-28 13:25:02

标签: java jpa eclipselink

我有一个字段LocalDate的课程,我想继续。

@Entity
public class Employee {
private Long id;    
private LocalDate issueDate;
// ... ///
// getters and setters
}

当我尝试通过执行

从数据库中获取对象时

Employee Employee = em.find(Employee.class, 1L)

我得到一个例外:

org.eclipse.persistence.exceptions.ConversionException /..../
could not be converted to [class java.time.LocalDate

然后我跟着那个tutorial并在LocalDate和String之间写了转换器。它有效,但使用EclipseLinkMariaDB我只能以这样的方式保持日期:“yyyy-MM-dd”。这样我就无法存储小时,分钟和秒钟。 EclipseLink提供以下异常:java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay。如何存储更精确的时间?

我的转换器:

@Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<LocalDate, String> {

    private static final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("yyyy-MM-dd").toFormatter();

    @Override
    public String convertToDatabaseColumn(LocalDate locDate) {
        return (locDate == null ? null : locDate.format(formatter));
    }

    @Override
    public LocalDate convertToEntityAttribute(String sqlDate) {
        return (sqlDate == null ? null : LocalDate.parse(sqlDate, formatter));
    }
}

1 个答案:

答案 0 :(得分:1)

我可以看到你的代码中有错误, 因为LocalDate没有时间参数所以你得到了那个例外。

要解决您的问题,您应该在DateTimeFormatter

中对代码进行更改
 private static final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("yyyy-MM-dd").toFormatter();

确保DateTimeFormatter

中没有时间attr
相关问题