我正在将 Spring Data 与 MongoDB 结合使用。
我有以下对象:
@Document(collection = "Notification")
public class Notification {
@Id
private String id;
@DBRef (lazy=true)
private User sender;
}
当我尝试使用以下方法返回此对象时,我在浏览器控制台中收到 500 错误
,并且看不到任何数据。
@RequestMapping(value = "/contactNotifications", method = RequestMethod.GET)
@ResponseBody
public List<Notification> getContactNotifications() {
List<Notification> notifications = notificationService.findByUser(user.getId());
return notifications;
}
但是,如果我删除 lazy=true
,它似乎确实有效。
如何在使用 lazy=true
时解决此问题?
最佳答案
您需要将lazy 设置为 false,以便在加载时加载与您的实体(用户)关联的所有实体(通知)。发生这种情况是因为它通过使用选择查询来获取您请求的用户,然后通过另一个查询获取与其关联的通知,当惰性为 true 时,该查询会被跳过,因此您必须将惰性设置为 false 或设置获取模式“加入”,这样它就会带来关联的实体。
这个link可能会对您有更多帮助。
关于java - Spring data DBRef 延迟加载 REST - 500 服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29884952/