Hibernate& JPA 2.1 - 将java.time.LocalDateTime映射为java.util.Map中的键

时间:2017-12-15 14:33:30

标签: java hibernate jpa jpa-2.1

以下枚举来自域模型类:

public enum OperationMode {
    BATTERY_CHANGE_MODE,
    PBP_MODE
}

我还定义了一个AttributeConverter来在LocalDateTime和TimeStamp之间进行转换

@Converter
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

   @Override
   public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
       return (locDateTime == null ? null : Timestamp.valueOf(locDateTime));
   }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
        return (sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime());
    }
}

在Entity类中,我需要将java.utitl.Map的工作映射定义为元素集合:

@ElementCollection
@MapKeyColumn(name = "time")
@Convert(converter = LocalDateTimeAttributeConverter.class)
// some annotations are missing here...
private Map<LocalDateTime, OperationMode> operationHistory;

推荐这种方法的推荐方法是什么?

1 个答案:

答案 0 :(得分:0)

解决方案是以下映射:

@ElementCollection
@MapKeyColumn(name = "time")
@Convert(converter = LocalDateTimeAttributeConverter.class, attributeName = "key")
@Enumerated(EnumType.STRING)
private Map<LocalDateTime, OperationMode> operationHistory;

attributeName &#39; key&#39; 缺失。