使用 LocalDate 从数据库实体中检索
Retrieve from DB entity with LocalDate
我有一个 class 字段 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之间的转换器。它有效,但使用 EclipseLink
和 MariaDB
我只能以这种方式保留日期:"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));
}
}
我可以看到你的代码有错误,
因为 LocalDate 没有时间参数所以你得到了那个例外。
要解决您的问题,您应该对 DateTimeFormatter
中的代码进行这些更改
private static final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd").toFormatter();
确保 DateTimeFormatter
中没有时间属性
我有一个 class 字段 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之间的转换器。它有效,但使用 EclipseLink
和 MariaDB
我只能以这种方式保留日期:"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));
}
}
我可以看到你的代码有错误, 因为 LocalDate 没有时间参数所以你得到了那个例外。
要解决您的问题,您应该对 DateTimeFormatter
private static final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd").toFormatter();
确保 DateTimeFormatter