【问题标题】:Spring data rest method not able to search on DbRef Id fieldSpring 数据休息方法无法在 DbRef Id 字段上进行搜索
【发布时间】:2018-04-29 14:25:42
【问题描述】:

我在我的应用程序中使用 mongodb 和 spring boot。在 Area 集合中,城市是 DBRef,但 spring 数据休息方法无法使用城市的 ID 进行搜索。它返回空 JSON,尽管对于那个城市,我的数据库中有区域。我的区域集合和存储库如下。

@Document(collection = "area")
    public class Area  {

      private String name;

      private String areaCode;

      private String postalCode;

      private String latitude;

      private String longitude;

      private String category;

      @DBRef(lazy = false)
      private City city;

public interface AreaRepo extends MongoRepository<Area, String> {

  @RestResource(path = "byCityId")
  List<Area> findByCityId(@Param(value = "cityId") String cityId);

其他集合中的相同关系是工作文件。

【问题讨论】:

    标签: java mongodb spring-boot spring-data-rest


    【解决方案1】:

    您可以尝试按城市搜索

    @Autowired 
    private CityRepository cityRepository;
    
    List<Area> findByCity(cityRepository.findByCityId(cityId));
    

    【讨论】:

      【解决方案2】:

      你可以添加@Query 注解。

      @Query("{ 'city': {'$ref': 'City', '$id': { '$oid': ?0 } } }")
      List<Area> findByCityId(@Param(value = "cityId") String cityId);
      

      或者直接用城市对象查找

      City city = new City(cityId);
      List<Area> findByCity(City city);
      

      【讨论】:

      • 感谢您的回复,但我遇到了以下错误。原因:java.lang.IllegalArgumentException:ObjectId 的无效十六进制表示:[_param_0]
      猜你喜欢
      • 1970-01-01
      • 2020-04-24
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多