Search code examples
hibernatehql

HQL not getting table name from Entity name


I have an Entity called Plan. This entity has an attribute Planner.

There is a scenario where a Planner leaves the company and his plans must be assigned to a different planner.

So I wrote this query in hql using the entity and attribute names:

String hql = "update Plan set planner = :newPlanner where planner = :oldPlanner";
Query query = getSession().createSQLQuery(hql);
query.setParameter("newPlanner", newPlanner);
query.setParameter("oldPlanner", oldPlanner);

However, when I try to execute it, Hibernate produces this:

Hibernate:
    update
        Plan
    set
        planner = ?
    where
        planner = ?
2017-03-03 08:56:31 TRACE BasicBinder:81 - binding parameter [2] as [BIGINT] - [5]
2017-03-03 08:56:31 TRACE BasicBinder:81 - binding parameter [1] as [BIGINT] - [6]
2017-03-03 08:56:31 WARN  SqlExceptionHelper:144 - SQL Error: 156, SQLState: S1000
2017-03-03 08:56:31 ERROR SqlExceptionHelper:146 - Incorrect syntax near the keyword 'Plan'.

So you see there is a problem here. My underlying table is called "plans" since "plan" is a keyword in SQL. My table also is part of a non-default schema.

It appears that HQL is not replacing "Plan" with "schema.plans" as it should nor is it replacing the column name for the planner which should be planner_id.

Am I doing something wrong here? I've coded other HQL without problems but those underlying table names matched the entity name and were all Select statements.

I guess I could just specify the underlying table name but does that mean I will have to specify the column names as well? My biggest concern is the schema. I use different schemas for different clients using the product. Therefore, I don't want to have any hard-coded schemas.


Solution

  • You're using createSQLQuery(). As its name suggests, this expects SQL, not HQL.