【问题标题】:Spring: How to get data from two table in JPASpring:如何从 JPA 中的两个表中获取数据
【发布时间】:2017-10-08 14:57:49
【问题描述】:

在下面的代码中,我想从 Order 表和 User 表中获取数据如何修改我的查询以便实现这一点? user_id 是订单表中的外键

public interface OrderRepository extends JpaRepository<Order, Long> {
 @Query("Select o from Order o where o.customer.id= :customerId and o.orderStatus='DELIVERED'")
     List<Order> orderHistory(@Param("customerId") long customerId);
     }

【问题讨论】:

标签: java mysql spring spring-data-jpa jpql


【解决方案1】:

要使用 Order 获取客户,请执行 join fetch

JOIN FETCH 表达式不是常规的 JOIN,它没有定义 JOIN 变量。它的唯一目的是指定应该从数据库中获取的相关对象以及同一往返行程中的查询结果。使用此查询提高了对结果 Country 对象的迭代效率,因为它消除了单独检索关联的 Capital 对象的需要。 http://www.objectdb.com/java/jpa/query/jpql/from

public interface OrderRepository extends JpaRepository<Order, Long> {
 @Query("Select o from Order o inner join fetch o.customer as customer left join fetch o.user as user where customer.id= :customerId and o.orderStatus='DELIVERED'")
     List<Order> orderHistory(@Param("customerId") long customerId);
     }

【讨论】:

  • 为什么inner和left同时加入?
  • 加载有订单的客户使用内连接。不确定您的模式用户是否对订单是强制性的,因此使用左连接。如果您的订单表总是有user_id,请将左连接更改为内连接。
【解决方案2】:

您想将 customerId 和 order 字段放入 param? 我认为列出参数中的订单字段就足够了。 当然sql语句一定是对的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2019-02-18
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多