您好,我在使用Lazy Load的Spring和Mongo时遇到了一些问题。
我有这个配置:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
本文件:
@Document
public class User {
@Id
private String id;
@DBRef
private Place place;
@DBRef(lazy=true)
private Country country;
.
.
.
}
一切正常,但当我曝光&#34;用户&#34;在RestController中,例如:
@RestController
public class UserController {
.
.
.
@RequestMapping(value = "user/{idUser}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public User getById(@PathVariable("idUser") String idUser){
return userService.getById(idUser);
}
}
输出结果为:
{
"id": "58ebf11ee68f2751f33ae603",
"place": {
"id": "58e3bf76e76877586435f5af",
"name": "Place X"
},
"country": {
"id": "58daa782e96139070bbc851c",
"name": "México",
"target":{
"id": "58daa782e96139070bbc851c",
"name": "México",
}
}
}
问题:
如果&#34; country&#34;标记为&#34; lazy = true&#34;,为什么打印出来?
为什么会有一个名为&#34; target&#34;的新字段在&#34;国家&#34;?
如何避免序列化字段标记为&#34; lazy = true&#34;?
提前感谢您的帮助。
答案 0 :(得分:2)
我在序列化结果中出现了与'target'类似的问题,并且能够通过创建自定义序列化程序来解决此问题,因此它序列化了实际对象,而不是具有“目标”的代理字段,并有一个时髦的类名。
显然,您可以选择不获取目标,而不是简单地获取目标并将其序列化,如下所示:
public class DBRefSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator generator, SerializerProvider provider)
throws JsonGenerationException, IOException {
provider.defaultSerializeValue(value, generator);
}
@Override
public void serializeWithType(Object value, JsonGenerator generator, SerializerProvider provider,
TypeSerializer typeSer)
throws IOException {
Object target = value;
if (value instanceof LazyLoadingProxy) {
LazyLoadingProxy proxy = (LazyLoadingProxy)value;
target = proxy.getTarget();
provider.defaultSerializeValue(target, generator);
} else {
provider.defaultSerializeValue(target, generator);
}
}
}
然后注释要运行它的DBRef,如下所示:
@JsonSerialize(using=DBRefSerializer.class)
@DBRef(lazy = true)
private SomeClass someProperty;
显然这对每个人来说并不完美,但我想我会发布它,以防它帮助其他人。
答案 1 :(得分:0)
添加@JsonIgnore注释。
@JsonIgnore
@DBRef(lazy = true)
private SomeClass someProperty;
来源: Cooperation MongoDB lazy loading with Jackson @JsonIgnore in SpringBoot Rest Controller