我正在使用spring数据mongodb,在进行延迟加载后,我收到错误"No serializer found for class org.springframework.data.mongodb.core.convert.DefaultDbRefResolver$LazyLoadingInterceptor"
。
我的域类是
public class Preference extends BaseEntity {
@DBRef(lazy = true)
User user;
MetadataEnum preferenceType;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public MetadataEnum getPreferenceType() {
return preferenceType;
}
public void setPreferenceType(MetadataEnum preferenceType) {
this.preferenceType = preferenceType;
}
public List<Subtype> getSubtypes() {
return subtypes;
}
public void setSubtypes(List<Subtype> subtypes) {
this.subtypes = subtypes;
}
List<Subtype> subtypes = new ArrayList<Subtype>();
boolean enableSearch;
}
我浪费了我的时间,但我无法得到合适的答案吗?有人可以帮我修复吗? 提前致谢
答案 0 :(得分:2)
根据您的要求添加此配置代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.convert.LazyLoadingProxy;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
@Configuration
public class LazyLoadingSerializationConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper om = new ObjectMapper();
final SimpleModule module = new SimpleModule("<your entity>", new Version(1, 0, 0,null));
module.addSerializer(LazyLoadingProxy.class, new LazyLoadingSerializer());
om.registerModule(module);
return om;
}
}
和
import java.io.IOException;
import org.springframework.data.mongodb.core.convert.LazyLoadingProxy;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class LazyLoadingSerializer extends JsonSerializer<LazyLoadingProxy> {
@Override
public void serialize(LazyLoadingProxy value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
jgen.writeStringField("id", value.toDBRef().getId().toString());
jgen.writeEndObject();
}
}
希望这可以帮到你!
答案 1 :(得分:0)
关闭该bean的序列化程序,因为@DBRef延迟加载仅适用于实体列表,jackson自动序列化@DBRef(lazy = true)列表用户,但不能序列化'@DBRef(lazy = true)用户用户。因此,您必须手动序列化它或关闭该bean的序列化程序。