Spring 基于嵌套对象和主体获取的数据查询
Spring data query to fetch based on nested object and principal
我有 Order 实体,它与 Customer
实体有 many-to-one
关系。我想编写一个 Spring 数据 JPA 查询来获取属于 customer id
.
的所有订单
下面是我的Order
实体
@Data
@NoArgsConstructor
@Builder
@AllArgsConstructor
@EqualsAndHashCode(exclude = "customer")
@ToString(exclude = "customer")
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private double price;
private LocalDate date;
@ManyToOne
@JoinColumn(name="customer_id", nullable = false)
@JsonBackReference
private Customer customer;
...
Spring 数据 JPA
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("select orders from Order where orders.customer.id = ?#{principal.id}")
Page<Order> findAll(Pageable pageable);
}
我哪里错了?我们也可以根据 Spring Data JPA.
中的方法命名约定使用流畅的风格编写上述查询
此 HQL 查询应该有效:
@Query("select o from Order o inner join o.customer c where c.id = ?#{principal.id}")
根据方法名查询好像不支持join操作,至少我找不到关键字。您可以查看 list of supported keywords.
的文档
我有 Order 实体,它与 Customer
实体有 many-to-one
关系。我想编写一个 Spring 数据 JPA 查询来获取属于 customer id
.
下面是我的Order
实体
@Data
@NoArgsConstructor
@Builder
@AllArgsConstructor
@EqualsAndHashCode(exclude = "customer")
@ToString(exclude = "customer")
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private double price;
private LocalDate date;
@ManyToOne
@JoinColumn(name="customer_id", nullable = false)
@JsonBackReference
private Customer customer;
...
Spring 数据 JPA
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("select orders from Order where orders.customer.id = ?#{principal.id}")
Page<Order> findAll(Pageable pageable);
}
我哪里错了?我们也可以根据 Spring Data JPA.
中的方法命名约定使用流畅的风格编写上述查询此 HQL 查询应该有效:
@Query("select o from Order o inner join o.customer c where c.id = ?#{principal.id}")
根据方法名查询好像不支持join操作,至少我找不到关键字。您可以查看 list of supported keywords.
的文档