I have a simple controller that return a User object, this user have a attribute coordinates that have the hibernate property FetchType.LAZY.
When I try to get this user, I always have to load all the coordinates to get the user object, otherwise when Jackson try to serialize the User throws the exception:
com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session
This is due to Jackson is trying to fetch this unfetched object. Here are the objects:
public class User{
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
@JsonManagedReference("user-coordinate")
private List<Coordinate> coordinates;
}
public class Coordinate {
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
@JsonBackReference("user-coordinate")
private User user;
}
And the controller:
@RequestMapping(value = "/user/{username}", method=RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String username) {
User user = userService.getUser(username);
return user;
}
There is a way to tell Jackson to not serialize the unfetched objects? I've been looking other answers posted 3 years ago implementing jackson-hibernate-module. But probably it could be achieved with a new jackson feature.
My versions are:
- Spring 3.2.5
- Hibernate 4.1.7
- Jackson 2.2