简体   繁体   中英

Hibernate & JPA 2.1 - mapping java.time.LocalDateTime as key in java.util.Map

The following enum is given from a domain model class:

public enum OperationMode {
    BATTERY_CHANGE_MODE,
    PBP_MODE
}

I also defined a AttributeConverter to convert between LocalDateTime and 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());
    }
}

In a Entity class I need to define a working mapping for java.utitl.Map as element collection:

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

What is the recommended method to get this working?

The solution is the following mapping:

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

attributeName 'key' was missing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM