Spring 使用 REST 延迟加载数据 DBRef - 500 服务器错误

Spring data DBRef lazy loading with REST - 500 server error

我正在使用 Spring 数据 MongoDB。

我有以下对象:

@Document(collection = "Notification")
public class Notification {
    @Id
    private String id;
    @DBRef (lazy=true)
    private User sender;
}

当我尝试使用以下方法 return 此对象时,我在浏览器控制台中收到 500 error 并且我看不到任何数据。

@RequestMapping(value = "/contactNotifications", method = RequestMethod.GET)
@ResponseBody
public List<Notification> getContactNotifications() {
    List<Notification> notifications = notificationService.findByUser(user.getId());
    return notifications;
}

但是,如果我删除 lazy=true,它似乎确实有效。

如何在使用 lazy=true 时解决此问题?

我认为 this 正是您的问题,所以不幸的是 没有(其他)解决方案而不是急切加载。

您需要将 lazy 设置为 false,以便它会在加载时加载与您的实体(用户)关联的所有实体(通知)。会发生这种情况是因为它通过使用 select 查询获取数据来获取您请求的用户,然后通过另一个查询获取与其关联的通知,当 lazy 为 true 时,该查询将被跳过,因此您必须将 lazy 设置为 false或将获取模式设置为 "join",这样它会带来关联的实体。

这个link可能对你有更多帮助。