-1

I have a simple RestController that returns a User Object after making calls to the DB by extending org.springframework.data.repository.PagingAndSortingRepository Interface.

The Challenge now is when I make this call for UserObject, addresses return Persistentbag Error

Error Exception occurred: com.sun.jdi.InvocationException occurred invoking method..

Snip of the Error

@Entity(name = "users")
public class UserEntity implements Serializable {

private static final long serialVersionUID = -2675537776836756234L;

 @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "userDetails", cascade = CascadeType.ALL)
private List<AddressEntity> address = new ArrayList<>();

//Constructors and Getters and Setters and toString()
}

@Entity(name="addresses")
public class AddressEntity implements Serializable {

private static final long serialVersionUID = 4209374923046988553L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@ManyToOne
@JoinColumn(name="users_id")
private UserEntity userDetails;

//Constructors and Getters and Setters and toString()
}

And the Controller

@RequestMapping(value = "/pagedList", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE,
        MediaType.APPLICATION_XML_VALUE })
public List<UserRest> getUsers(@RequestParam(value = "page", defaultValue = "0") int page,
        @RequestParam(value = "limit", defaultValue = "25") int limit) {
    List<UserRest> returnvalue = new ArrayList<>();
    List<UserDTO> userDTO = userService.getUsers(page, limit);
    for (UserDTO source : userDTO) {
        UserRest target = modelMapper.map(source, UserRest.class);
        target.setDate(source.getCreatedAt());
        returnvalue.add(target);
    }
    return returnvalue;
}

The UserService Class:

public List<UserDTO> getUsers(int page, int limit) {
    List<UserDTO> returnvalue = new ArrayList<>();
    if (page > 0)
        page -= 1;
    Pageable pageableRequest = PageRequest.of(page, limit);
    Page<UserEntity> usersPage = userRepo.findAll(pageableRequest);//Returns Nothing for addresses at this point
    List<UserEntity> users = usersPage.getContent();

    for (UserEntity source : users) {
        returnvalue.add(modelMapper.map(source, UserDTO.class));
    }
    return returnvalue;
}

Thanks

nwabudo
  • 11
  • 4
  • Please post a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of your problem, to make it easier for others to figure out what is wrong. – bartolo-otrit Mar 07 '20 at 09:16

1 Answers1

0

So I found out that changing the annotation to

@OneToMany(fetch = FetchType.EAGER, mappedBy = "userDetails", cascade = CascadeType.ALL)

Solved the issue.

Thank you all

nwabudo
  • 11
  • 4