最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

hibernate - JPA Converter for field within @Embeddable not working - Stack Overflow

programmeradmin5浏览0评论

I'm moving from Hibernate UserType to JPA Converters, but I have one issue it seems the Converter are not used for fields within @Embedded objects, here is the example

Parent class contains:

  @Embedded
  @AttributeOverrides({
      ...
      @AttributeOverride(name = "objectMap", column = @Column(name = "arr_object_map")),
      ....
  })
  public CustomData getCustomDataForArrival() {
    return arrivalCustomData;
  }

  @Embedded
  @AttributeOverrides({
      ...
      @AttributeOverride(name = "objectMap", column = @Column(name = "dep_object_map")),
      ....
  })
  
  public CustomData getCustomDataForDeparture() {
    return departureCustomData;
  }

The embedded object:

@Embeddable
public class CustomData {

  ....

  private CustomMap customMap = new CustomMap();

  @Convert(converter = CustomMapConverter.class)
  public CustomMap getCustomMap() {
    return customMap;
  }

}

The type of the embedded object:

public class CustomMap extends TreeMap<MyObject, String> {

}

The converter I have created:

@Converter(autoApply = true)
public class CustomMapConverter implements AttributeConverter<CustomMap, String> {
  private final ObjectMapper mapper = new ObjectMapper();

  public CustomMapConverter() {
  }

  @Override
  public String convertToDatabaseColumn(CustomMap customMap) {
    try {
      return mapper.writeValueAsString(customMap);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public CustomMap convertToEntityAttribute(String str) {
    try {
      if (StringUtils.isEmpty(str)) {
        return new CustomMap();
      } else {
        return mapper.readValue(str, CustomMap.class);
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}

Even with all of that, when we save/get object to/from database Hibernate is trying to serialize them using basic Java serialization, which of course fails as I expect to use Jackson here with my custom mapper. It seems the converter is not taken into account at all, am I missing something ?


Edit: one observation i've made is that it works if I change all instances of CustomMap to the a type like Map<MyObject, String> without using the custom interface above

发布评论

评论列表(0)

  1. 暂无评论