0

I am using Java 1.7. I have a REST service, when I call it, I get the following error when it tries to map the Java object to JSON:

HTTP Status 500 - org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: entity.Person.flightPreferences, no session or session was closed (through reference chain: com.nexct.auth.model.UserDetailsAndRoles["person"]->entity.Person["approver"]->entity.approval.AutoApprovalApproverConfiguration["approver"]->entity.Person["flightPreferences"])

and

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: entity.Person.flightPreferences, no session or session was closed

Code:

Person.java

@OneToMany(cascade = CascadeType.ALL)
@JsonIgnore
public List<TravellerFlightPreference> getFlightPreferences()
{
    return flightPreferences;
}

This post suggested to add @JsonIgnore, but I still get the error.

AuthenticationResource.java

@GET
@Path("/details")
@ApiOperation(value="Get user details for a user held in the jwt")
@ApiResponses({
        @ApiResponse(code=200, message="Success"),
        @ApiResponse(code=404, message="Not Found")
})
@Produces({ MediaType.APPLICATION_JSON })
public Response details(@HeaderParam("Authorization") String token, @Context HttpServletRequest request) {
    UserDetailsAndRoles userDetailsAndRoles = new UserDetailsAndRoles();
    String jwtToken = getJwtToken(token);
    String userName = jwtTokenUtil.extractUserName(jwtToken);
    Set<Role> memberRoles = new HashSet<>();
    Set<UserRole> userRoles = new HashSet<>();
    try {
        Member member = memberService.getMemberByUserName(userName);
        Person person = personService.getPersonEntityByMemberId(member.getId());
        //List<TravellerFlightPreference> travellerFlightPreferences = person.getFlightPreferences();
        List<Employee> employees = employeeService.findEmployeeByMemberId(member.getId());
        Contact contact = loginLocal.findContactMemberId(member.getId());
        List<Account> accounts = loginLocal.findAllAccountByMemberId(member.getId());
        memberRoles = roleManager.viewRolesAssignedToMember(new ViewRolesAssignedToMemberRequest(member.getId())).getRoles();
        for (Role role: memberRoles) {
            UserRole userRole = new UserRole();
            userRole.setId(role.getId());
            userRole.setName(role.getName());
            userRole.setDescription(role.getDescription());
            userRoles.add(userRole);
        }
        userDetailsAndRoles.setAccounts(accounts);
        userDetailsAndRoles.setContact(contact);
        userDetailsAndRoles.setEmployees(employees);
        userDetailsAndRoles.setMember(member);
        userDetailsAndRoles.setPerson(person);
        userDetailsAndRoles.setUserRoles(userRoles);
        //userDetailsAndRoles.setTravellerFlightPreferences(travellerFlightPreferences);
    } catch (MemberDoesNotExistException e) {
        logger.severe("Error getting member for userName: "+userName);
        e.printStackTrace();
        return Response.ok(null, "Error getting member for userName: "+userName+". "+e.getMessage()).build();
    }
    return Response.ok().entity(userDetailsAndRoles).build();
}

I think this error is because the flightPreferences are not loaded when the Person object is converted to JSON.

Question

  • In the Person object, I do not tell Hibernate to Laizily load the flightPreferences, why are they not available?
  • When I add the @JsonIgnore, why does it still get the error?
Richard
  • 8,193
  • 28
  • 107
  • 228
  • 1
    Check you are using right import for `@JsonIgnore` ? means are you want to use `fasterxml` or `codehaus`. The post suggest `@JsonIgnore` of `fasterxml` – Eklavya Aug 11 '20 at 15:04
  • My import is: `import com.fasterxml.jackson.annotation.JsonIgnore;`. Which I think is correct. For the response object I build, I use `import javax.ws.rs.core.Response`. The other option I have from my dependencies is `import net.minidev.json.annotate.JsonIgnore;`. I will test this. – Richard Aug 11 '20 at 15:29
  • 1
    In error I see `org.codehaus.jackson.map.JsonMappingException` that's why I am confused ? – Eklavya Aug 11 '20 at 15:30
  • When I try `import net.minidev.json.annotate.JsonIgnore;`, it also just gets ignored. – Richard Aug 11 '20 at 15:33
  • I am going to try the following: `@JsonIgnoreProperties(ignoreUnknown = true)` (`import com.fasterxml.jackson.annotation.JsonIgnoreProperties;`) - no difference, I get the same error – Richard Aug 11 '20 at 15:36

0 Answers0