问题
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