Spring MongoDB + QueryDSL查询由@DBRef相关列表


@Document(collection="users")
public class User{
  @Id
  private int id;
  private String name;
  ...
  //getters-setters
}
@Document(collection="models")
public class Model{
  @Id
  private int id;
  private String name;
  @DBRef
  private List<User> users;
  ...
  //getters-setters
}

我尝试了这个解决方案,但它没有返回任何东西:

QModel model = new QModel();page = new PageRequest(0,100);

return modelsRepository.findAll(model.users.any().id.eq(anUserId), pageable);

我认为这一切都取决于MongoDB收集的JSON数据。

在您的例子中,"models"集合应该有一个"users" Array的属性。只要键名是匹配的(即。

详细的例子:-

下面的例子可以正常工作。

人收集:-

{
    "_id" : ObjectId("57c8269b3ee7df409d4d2b64"),
    "name" : "Erin",
    "places" : [ 
        {
            "$ref" : "places",
            "$id" : ObjectId("57c813b33ee7df409d4d2b58")                
        }
    ],
    "url" : "bc.example.net/Erin"
}

地方集合:-

{
    "_id" : ObjectId("57c813b33ee7df409d4d2b58"),
    "name" : "Broadway Center",
    "url" : "bc.example.net"
}

: -

地方类:-

@Document(collection = "places")
public class Places implements Serializable {
    private static final long serialVersionUID = -5500334641079164017L;
    @Id
    private String id;
    private String name;
    private String url;
    ...get and setters
}

人类:-

@Document(collection = "people")
public class People implements Serializable {
    private static final long serialVersionUID = 6308725499894643034L;
    @Id
    private String id;
    private String name;
    @DBRef
    private List<Places> places;
    private String url;
    ...get and setters
}

库类:-

@Repository
public interface PeopleRepository extends PagingAndSortingRepository<People, String> {
    public People findById(String id);
    @Query(value = "{ 'status' : ?0 }")
    public Page<People> findByStatus(String status, Pageable pageable);
}

FindAll: -

public Boolean findAllPeople() {
        Page<People> peoplePage = peopleRepository.findAll(new PageRequest(0, 20));
        System.out.println("Total elements :" + peoplePage.getTotalElements());
        for (People people : peoplePage) {
            System.out.println("People id :" + people.getId());
            System.out.println("Place size :" + people.getPlaces().size());
            people.getPlaces().forEach(p -> System.out.println(p.getName()));
        }
        return true;
    }

相关内容

  • 没有找到相关文章

最新更新