Hello I have some issues with Spring and Mongo with Lazy Load.
I have this configuration:
<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>
This Document:
@Document
public class User {
@Id
private String id;
@DBRef
private Place place;
@DBRef(lazy=true)
private Country country;
.
.
.
}
Everything works fine, but when I expose the "User" in a RestController, for example:
@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);
}
}
The output is:
{
"id": "58ebf11ee68f2751f33ae603",
"place": {
"id": "58e3bf76e76877586435f5af",
"name": "Place X"
},
"country": {
"id": "58daa782e96139070bbc851c",
"name": "México",
"target":{
"id": "58daa782e96139070bbc851c",
"name": "México",
}
}
}
Questions:
If "country" is marked as "lazy=true", why it is printed out?
Why there is a new field named "target" in "country"?
How can I avoid serialize fields marked as "lazy=true"?
thanks in advance for your help.
I had a similar issue with the 'target' showing up in the serialized results, and was able to solve this issue by creating a custom serializer so it serializes the actual object, and not the proxy, which has the 'target' field and has a funky class name.
Obviously, you could choose to not fetch the target instead of simply fetching it and serializing it as is shown here:
And then annotate the DBRefs you want to run through it like this:
Obviously this isn't perfect for everyone, but I figured I would post it in case it helps someone else.