繁体   English   中英

Spring数据REST findBy嵌套实体

[英]Spring data REST findBy nested entity

我有一个使用Spring-data-rest的Spring Boot项目来生成我的REST接口,我试图允许嵌套资源的分页。 我遵循这个解决方法,并坚持实现findBy查询。

我有以下设备实体:

@Entity
@Table(name = "devices")
public class Device extends ResourceSupport {

  ...

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "user_id")
  private User user;
}

我需要使用userId查询它:

@RequestMapping(path = "/users/{id}/devices", method = RequestMethod.GET)
public ModelAndView getUserDevices(@PathVariable Integer id) {
    return new ModelAndView("forward:/devices/search/findByUserId?userId=" + id);
}

所以我在DeviceRepository中创建了以下方法:

@Repository
public interface DeviceRepository extends JpaRepository<Device, Long> {

  @PreAuthorize("hasRole('ROLE_ADMIN') OR @securityCheck.check(#user, authentication)")
  Page<Device> findByUserId(@Param("user") User user, Pageable pageable);

}

但是在尝试向此端点发送请求时,我收到以下异常:

Unable to locate Attribute  with the the given name [id] on this ManagedType [com.example.User]

有没有人有一些建议我做错了什么?

编辑:谢谢你的回复,我改变了方法

Page<Device> findByUser_UserId(@Param("user") User user, Pageable pageable);

我的用户实体包含userId字段。

但是,现在我收到以下异常:

{
    "cause": {
        "cause": {
            "cause": null,
            "message": "Cannot resolve URI 1. Is it local or remote? Only local URIs are resolvable."
        },
        "message": "Failed to convert from type [java.net.URI] to type [@org.springframework.data.repository.query.Param com.example.User] for value '1'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI 1. Is it local or remote? Only local URIs are resolvable."
    },
    "message": "Failed to convert 1 into me.originalsin.user.model.User!"
}

所以我似乎错误地使用了查询?

请查看文档

属性表达式只能引用被管实体的直接属性,如前面的示例所示。 在查询创建时,您已确保已解析的属性是托管域类的属性。 但是,您也可以通过遍历嵌套属性来定义约束。 假设一个人有一个带ZipCode的地址。 在这种情况下,方法名称为

List<Person> findByAddressZipCode(ZipCode zipCode);

[...]虽然这应该适用于大多数情况,但算法可能会选择错误的属性。 假设Person类也有一个addressZip属性。 该算法将在第一个拆分轮中匹配,并且基本上选择了错误的属性并最终失败(因为addressZip的类型可能没有代码属性)。 要解决这种歧义,可以在方法名称中使用_来手动定义遍历点。 所以我们的方法名称最终会像这样:

List<Person> findByAddress_ZipCode(ZipCode zipCode);

这意味着:除了您的Device类具有字段userId之外,您所做的工作应该有效。

您向我们展示的例外是原始问题中的以下内容。

无法在此ManagedType [com.example.User]上找到具有给定名称[id]的Attribute

这看起来像您的类User没有名为id的字段。 既然你没有向我们展示这个类的代码我就不知道是不是这样。 (确保在存储库中导入了正确的User类)

问题已更新,因此另一个答案存在另一个错误

现在的问题是您将User对象传递给存储库方法,但按ID过滤。 只需将第一个参数更改为用户标识的数据类型即可。 我认为这应该有效。

假设id的类型为int该方法可能如下所示

Page<Device> findByUser_UserId(@Param("userId") int userId, Pageable pageable);

尝试

 Page<Device> findByUser_Id(@Param("user") User user, Pageable pageable);

由于您要在DeviceRepository中创建方法,并且要在嵌套字段(user.id)上进行搜索,因此需要使用“_”进行引用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM