I have Order entity which has a many-to-one
relationship with Customer
entity. I want to write a Spring Data JPA query to fetch all the orders that belong to the customer id
.
Below is my Order
entity
@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 Data 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);
}
Where am I going wrong? Also can we write the above query using fluent-style based on the method naming convention in Spring Data JPA.
CodePudding user response:
This HQL query should work:
@Query("select o from Order o inner join o.customer c where c.id = ?#{principal.id}")
The query based on the method name doesn't seem to support join operations, or at least I couldn't find the keyword. You can check the documentation for the list of supported keywords.