Search code examples
javahibernatespring-datajpql

JPQL JOIN on Foreign Key causes SQLSyntaxErrorException


I have two entities Order and Customer. Order has a @ManyToOne relationship with Customer. However, when I declare the following JPQL query, I get an SQLSyntaxErrorException because the generated SQL is missing the ON condition.

JPQL:

SELECT o.id,
       o.incrementId,
       o.externalId,
       o.state,
       o.status,
       o.couponCode,
       o.totalDiscount,
       o.total,
       o.originChannel,
       o.branchOffice,
       o.createdAt,
       o.updatedAt,
       c.fullName
FROM Order o
JOIN FETCH Customer c;

Generated SQL:

select order0_.id             as col_0_0_,
       order0_.increment_id   as col_1_0_,
       order0_.external_id    as col_2_0_,
       order0_.state          as col_3_0_,
       order0_.status         as col_4_0_,
       order0_.coupon_code    as col_5_0_,
       order0_.total_discount as col_6_0_,
       order0_.total          as col_7_0_,
       order0_.origin_channel as col_8_0_,
       order0_.branch_office  as col_9_0_,
       order0_.created_at     as col_10_0_,
       order0_.updated_at     as col_11_0_,
       customer1_.full_name   as col_12_0_
from orders order0_
inner join customers customer1_ on;

As you can see, it's missing the condition on. I find that strange, because these are my entities:

Order (Irrelevant properties omitted for brevity)

@Entity
@Table(name = "orders")
public class Order {
    
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private int id;
    
   @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
   @JoinColumn(name = "customer_id", referencedColumnName = "id", table = "orders")
   private Customer customer;
    
   public Customer getCustomer() {
       return customer;
   }
}

Customer (Irrelevant properties omitted for brevity)

My use case doesn't require that I have a List<Order> in the Customer entity (I tried adding it and that doesn't solve the problem anyway.

@Entity
@Table(name = "customers")
public class Customer {
    
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private int id;
    
   public int getId() {
      return id;
   }
    
   public void setId(int id) {
      this.id = id;
   }
}

The relationship between these two entities is correct because it works as expected when it comes to inserting, updating and retrieving by normal means. Am I missing something here?


Solution

  • Try to use the following jpql:

    select o from Order o join o.customer
    

    See also the documantation.