Spring data REST findBy nested entity

◇◆丶佛笑我妖孽 提交于 2019-12-05 10:42:49

Please have a look at the docs.

Property expressions can refer only to a direct property of the managed entity, as shown in the preceding example. At query creation time you already make sure that the parsed property is a property of the managed domain class. However, you can also define constraints by traversing nested properties. Assume a Person has an Address with a ZipCode. In that case a method name of

List<Person> findByAddressZipCode(ZipCode zipCode);

[...] Although this should work for most cases, it is possible for the algorithm to select the wrong property. Suppose the Person class has an addressZip property as well. The algorithm would match in the first split round already and essentially choose the wrong property and finally fail (as the type of addressZip probably has no code property). To resolve this ambiguity you can use _ inside your method name to manually define traversal points. So our method name would end up like so:

List<Person> findByAddress_ZipCode(ZipCode zipCode);

That means: what you did should work, except the case your Device class has a field userId.

The exception you showed to us was the following in the original question.

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

This looks like your class User does not have a field called id. Since you did not show us the code of this class i cant tell if that's the case or not. (Make sure that you imported the correct User class in your repository)

Question has been updated and therefore ANOTHER error exists with ANOTHER answer

The problem now is that you pass a User object to your repository method but filter by an id. Just change the first parameter to the datatype of the user id. I think that should work.

Assuming the type of id is int the method could look like this

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

Try

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

Since you are creating a method in DeviceRepository, and you want to search on a nested filed(user.id), You need to reference it using "_"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!