2

In Hibernate, I created a query using JOIN to join two tables. The query executes fine in Oracles SQL Developer. However, if I add it to a @NamedQuery, the server starts with this error:

Error in named query: loadFooByAnother: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ON near line 1, column xxx

My named query is:

SELECT foo FROM FooTable foo JOIN BarTable bar
  ON foo.something=bar.somethingId
    WHERE bar.anotherId=:another

Is it not possible to use JOIN .. ON syntax in Hibernate?

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
user1438038
  • 5,821
  • 6
  • 60
  • 94

1 Answers1

3

You need to use the with directive, if you use HQL:

SELECT foo 
FROM FooEntity foo 
JOIN foo.bar b with b.name = :name
WHERE foo.prop = :prop

This is for supplying a custom ON clause. From your example, judging from how you joined tables, I think you tried to execute a native SQL using a @NamedQuery.

If you want to run a native SQL query, you have to use @NamedNativeQuery instead.

If you want to use HQL, you need to use Entities and to join Entity associations (not tables).

If you use JPQL then the with directive has to be replaced by the on directive, but again, you need to navigate entity associations, meaning you have to map them first.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • Thank you for pointing out that there is ``@NamedQuery`` and ``@NamedNativeQuery``. I mixed up native SQL and HQL then. The only reference for the ``WITH`` keyword is in [this article](https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-joins), though. – user1438038 Feb 04 '15 at 14:05