0

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.

1
  • Can you add the Customer entity? Commented May 28, 2022 at 18:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.