5

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.

Marius L
  • 336
  • 1
  • 7
  • 2
    I just added a related pull request: https://github.com/querydsl/querydsl/pull/804 – Timo Westkämper Jun 13 '14 at 20:38
  • 1
    @TimoWestkämper I'm unable to make the following request work userRepository.findAll(order.user.username.eq(someUsername), pageable); It works fine with the referenced id userRepository.findAll(order.user.id.eq(anUserId), pageable); – Philippe Nov 27 '17 at 16:38
  • 1
    @Philippe I have the same issue. Did you find any solution for that? – Nishant Bhardwaz Nov 28 '17 at 09:22

1 Answers1

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).

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277