1. 程式人生 > >SpringBoot中測試Elasticsearch,在測試ElasticsearchRepository文件操作中的查詢時報錯org.springframework.data.elasticsearch.ElasticsearchException: failed to map source **

SpringBoot中測試Elasticsearch,在測試ElasticsearchRepository文件操作中的查詢時報錯org.springframework.data.elasticsearch.ElasticsearchException: failed to map source **

問題描述

在SpringBoot中測試Elasticsearch的時候,當測試ElasticsearchRepository的文件操作的時候,在呼叫find()查詢方法時報錯,錯誤如下

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.zmx.elasticsearch.pojo.Item` (no Creators, like default construct, exist): 
cannot deserialize from Object value (no delegate
- or property-based Creator) at [Source: (String); line: 1, column: 2] at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67) at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452) at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:
1028) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1297) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159
) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004) at org.springframework.data.elasticsearch.core.DefaultEntityMapper.mapToObject(DefaultEntityMapper.java:82) at org.springframework.data.elasticsearch.core.AbstractResultMapper.mapEntity(AbstractResultMapper.java:43) ... 56 more
 

原因

這是因為在實體類Item中為了方便例項化添加了一個有參建構函式,導致JVM不能新增預設的無參構造函數了,但是jackson的反序列化需要使用無參建構函式,所以報錯!

解決

在實體類Item中新增一個無參建構函式就可以了!