Spring MongoDB + QueryDSL query by @DBRef related object

吃可爱长大的小学妹 提交于 2019-12-12 09:40:00

问题


I am using spring-data-mongodb and querydsl-mongodb to perform more flexible queries.

My application has users and orders. An user can have multiple orders, so my models looks like this:

public class User {

  @Id
  private String id;
  private String username;

 //getters and setters
}

public class Order {
  @Id
  private String id;

  @DBRef
  private User user;

  //getters and setters
}

As you can see, there is an has-many relationship between users and orders. Each order is assigned to an user, and the user is stored in @DBRef public User user attribute.

Now, lets say that an user has 10,000 orders.

How can i make the query to get all orders that belongs to an specific user ?

I have the OrderRepository:

public interface OrderRepository extends MongoRepository<Order, String>,
        QueryDslPredicateExecutor<Order> {

}

I tried this solution but it doesnt return anything:

QOrder order = new QOrder("order");
Pageable pageable = new PageRequest(0, 100);

return userRepository.findAll(order.user.id.eq(anUserId), pageable);

I need to use querydsl because i want to build a service that can query orders by more many prameters than userid. For example i want to get all orders that belongs to user with specific username.


回答1:


No need for QueryDSL when searching by ID. In OrderRepository, create an interface method:

public List<Order> findByUser(String userId);

Request example: curl http://localhost:8080/orders/search/findByUser?userId=5a950ea0a0deb42729b570c0

* I'm stuck on how to query orders, for example, of all users from certain city (some mongo join with user and address).



来源:https://stackoverflow.com/questions/24202259/spring-mongodb-querydsl-query-by-dbref-related-object

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