使用CustomEntityMapper时,未在读取时填充spring-data-elastic Id字段

时间:2017-02-10 19:09:40

标签: spring-data-elasticsearch

Elasticversion - 1.7.6 springboot - 1.3.5

使用spring-data-elasticsearch我已经在其他地方建议了一个自定义JSON映射,以支持Java8新的datetime字段。 这样可以正常工作 - 但是当不再填充id字段时,会从存储库中删除读取实体。

CustomConfig:

@Bean
@Autowired
public ElasticsearchTemplate elasticsearchTemplate(Client client) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    return new ElasticsearchTemplate(client, new CustomEntityMapper(objectMapper));
}

public class CustomEntityMapper implements EntityMapper {

    private ObjectMapper objectMapper;

    public CustomEntityMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    }

    @Override
    public String mapToString(Object object) throws IOException {
        return objectMapper.writeValueAsString(object);
    }

    @Override
    public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
        return objectMapper.readValue(source, clazz);
    }
}

示例实体:

@Document(indexName = "scanner", type = "Entry")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Entry {
    @Id
    private String id;

    @Field(type= FieldType.String)
    private String path;

    @Field(type = FieldType.Date, format = DateFormat.date_time )
    private OffsetDateTime created;

}

注意 - 当我删除CustomEntityMapper时,会返回id字段。我已经跟踪了spring-data-elasticsearch代码, 并确定它无法解决DefaultResultMapper.setPersistentId中弹性响应的Id字段 mappingContext为null。

private <T> void setPersistentEntityId(T result, String id, Class<T> clazz) {
        if (mappingContext != null && clazz.isAnnotationPresent(Document.class)) {
            PersistentProperty<ElasticsearchPersistentProperty> idProperty = mappingContext.getPersistentEntity(clazz).getIdProperty();
            // Only deal with String because ES generated Ids are strings !
            if (idProperty != null && idProperty.getType().isAssignableFrom(String.class)) {
                Method setter = idProperty.getSetter();
                if (setter != null) {
                    try {
                        setter.invoke(result, id);
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            }
        }
    }

有没有人遇到过这个问题?如何在不破坏Id分辨率的情况下支持CustomEntityMapper?

1 个答案:

答案 0 :(得分:0)

升级到spring boot 1.4.1-RELEASE解决了问题