Spring MongoDB + QueryDSL 通过@DBRef 相关对象查询 [英] Spring MongoDB + QueryDSL query by @DBRef related object

查看:49
本文介绍了Spring MongoDB + QueryDSL 通过@DBRef 相关对象查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 spring-data-mongodb 和 querydsl-mongodb 来执行更灵活的查询.

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
}

如您所见,用户和订单之间存在多方关系.每个订单分配给一个用户,该用户存储在@DBRef公共User用户属性中.

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.

现在,假设用户有 10,000 个订单.

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 ?

我有 OrderRepository:

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

我需要使用querydsl,因为我想构建一个服务,该服务可以通过比userid更多的参数来查询订单.例如,我想获取属于具有特定用户名的用户的所有订单.

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.

推荐答案

按 ID 搜索时无需 QueryDSL.在OrderRepository中,创建一个接口方法:

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

public List<Order> findByUser(String userId);

请求示例:curl http://localhost:8080/orders/search/findByUser?userId=5a950ea0a0deb42729b570c0

* 我被困在如何查询订单,例如,来自某个城市的所有用户的订单(一些 mongo 加入用户和地址).

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

这篇关于Spring MongoDB + QueryDSL 通过@DBRef 相关对象查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆