你好,我在使用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;
.
.
.
}
一切正常,但是当我在RestController中公开“User”时,例如:
@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",
}
}
}
问题:
>如果“country”被标记为“lazy = true”,为什么打印出来?
>为什么在“country”中有一个名为“target”的新字段?
>如何避免序列化标记为“lazy = true”的字段?
在此先感谢您的帮助.
最佳答案 我在序列化结果中出现了类似的“目标”问题,并且能够通过创建自定义序列化程序来解决此问题,因此它序列化了实际对象,而不是代理,它具有“目标”字段并具有一个时髦的班级名称.
显然,您可以选择不获取目标,而不是简单地获取目标并将其序列化,如下所示:
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;
显然这对每个人来说并不完美,但我想我会发布它,以防它帮助其他人.