org.hibernate.hql.ast.QuerySyntaxException: unexpected token: jpa

2k Views Asked by At

After adding AND condition to the below mentioned query

  String querys = "SELECT dr.id,dr.creation_time,dr.drawing_spec_format,dr.end_time,dr.error_type,dr.last_access_time,dr.server_name,dr.start_time,dr.supply_unit,dr.client_id,ds.request_id,ds.bb,ds.car_offset_g,ds.car_sling_type,ds.car_type,ds.ch,ds.country"
            + " FROM FlcDrawingRequests dr, FlcDrawingRequestStats ds "
            + " where dr.id=ds.request_id"
            + " AND "
            + "(dr.start_time > "
            + monthStartDate
            + ")"
            + " AND "
            + "(dr.start_time <= "
            + monthEndDate + ")";

i am getting the below exception

 java.lang.IllegalArgumentException: 
         org.hibernate.hql.ast.QuerySyntaxException: unexpected token: 00 near line 1, column 851 [SELECT dr.id,dr.creation_time,dr.drawing_spec_format,dr.end_time,dr.error_type,dr.last_access_time,dr.server_name,dr.start_time,dr.supply_unit,dr.client_id,ds.request_id,ds.bb,ds.car_offset_g,ds.car_sling_type,ds.car_type,ds.ch,ds.country FROM com.kone.kss.cad.flcws.FlcDrawingRequests dr, com.kone.kss.cad.flcws.FlcDrawingRequestStats ds  where dr.id=ds.request_id AND (dr.start_time > 2019-04-01 00:00:00) AND (dr.start_time <= 2019-4-2 23:59:59)]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:624)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:96)

Could you please help me on this issue!

1

There are 1 best solutions below

8
On

This answer assumes that you are trying to execute a native query. In any case, you should be using a prepared statement, and this would actually resolve the source of the error, which has to do with unquoted date literals.

String sql = "SELECT dr.id, dr.creation_time, dr.drawing_spec_format, dr.end_time, dr.error_type, dr.last_access_time, dr.server_name, dr.start_time, dr.supply_unit, dr.client_id, ds.request_id, ds.bb, ds.car_offset_g, ds.car_sling_type, ds.car_type, ds.ch, ds.country ";
sql += "FROM FlcDrawingRequests dr ";
sql += "INNER JOIN FlcDrawingRequestStats ds ";
sql += "ON dr.id = ds.request_id AND ";
sql += "dr.start_time > ?1 AND ";
sql += "dr.start_time <= ?2";

Query q = em.createNativeQuery(sql);

q.setParameter(1, monthStartDate);
q.setParameter(2, monthEndDate);

Note that I have also replaced your old school implicit joins with explicit inner joins. This is the preferred way of writing a join in modern SQL.