JPA,JPQL: unexpected token: LEFT near line 1 - java

I want to display all the checklists that are not answered and not answered (response checklists is in the ResponsesCheckLists table) using the following parameters: idequipement and idMission.
#Query("SELECT check,resp,eq FROM Equipements eq INNER JOIN CheckLists check WHERE eq.idEquipements = check.equipements.idEquipements LEFT JOIN ResponsesCheckLists resp ON check.idCheckLists=resp.CheckLts.idCheckLists AND resp.Respmission.idMission = :idmiss WHERE eq.idEquipements = :idEqp ")
public List<ResponsesCheckLists> ListCheckListsNonRepondu(#Param("idEqp") long idEqp, #Param("idmiss") long idmiss);
After running this query, I displays this error message:
antlr.NoViableAltException: unexpected token: LEFT
------
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: LEFT near line 1, column 148 [SELECT check,resp,eq FROM com.SSC.DAO.Entities.Equipements eq INNER JOIN CheckLists check WHERE eq.idEquipements = check.equipements.idEquipements LEFT JOIN ResponsesCheckLists resp ON check.idCheckLists=resp.CheckLts.idCheckLists AND resp.Respmission.idMission = :idmiss WHERE eq.idEquipements = :idEqp ]
------
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'responsesCheckListsRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.SSC.DAO.JPARepository.ResponsesCheckListsRepository.ListCheckListsNonRepondu(long,long)!
Edit1:
#Query("SELECT check,resp,eq FROM Equipements eq INNER JOIN CheckLists check ON eq.idEquipements = check.equipements.idEquipements"
+ " INNER JOIN ResponsesCheckLists resp ON check.idCheckLists=resp.CheckLts.idCheckLists AND resp.Respmission.idMission = :idmiss AND eq.idEquipements = :idEqp ")
public List<ResponsesCheckLists> ListCheckListsNonRepondu(#Param("idEqp") long idEqp, #Param("idmiss") long idmiss);
Error of Edit1;
Caused by: java.lang.IllegalStateException: No data type for node:
org.hibernate.hql.internal.ast.tree.IdentNode +-[IDENT] IdentNode:
'check' {originalText=check}
antlr.SemanticException: Path expected for join!
Caused by: java.lang.IllegalArgumentException: Validation failed for
query for method public abstract java.util.List
com.SSC.DAO.JPARepository.ResponsesCheckListsRepository.ListCheckListsNonRepondu(long,long)!
Edit2:
#Query("SELECT check , resp , eq FROM Equipements eq INNER JOIN CheckLists check ON eq.idEquipements = check.equipements.idEquipements"
+ " INNER JOIN ResponsesCheckLists resp ON check.idCheckLists=resp.CheckLts.idCheckLists AND resp.Respmission.idMission = :idmiss AND eq.idEquipements = :idEqp ")
public List<ResponsesCheckLists> ListCheckListsNonRepondu(#Param("idEqp") long idEqp, #Param("idmiss") long idmiss);
Errors of Edit2:
Caused by: java.lang.IllegalStateException: No data type for node:
org.hibernate.hql.internal.ast.tree.IdentNode +-[IDENT] IdentNode:
'check' {originalText=check}
antlr.SemanticException: Path expected for join!
How to correct this query?
thank you in advance

You have a Spring annotation there (#Query) that specifies a JPQL query. Your JPQL query is supposed to follow the syntax highlighted in this link (and the JPA spec). Sadly you haven't followed that.
SELECT {result} FROM {from} WHERE {where} ...
Any "JOIN" has to go in the FROM clause. You already put one JOIN in the FROM clause, but for reasons only known to you, you decided to put another JOIN in the WHERE clause!! In fact you have 2 WHERE clauses in that crap.
It is impossible to tell you what your query should be because you don't post your entities, so we don't see what relations they have, or even what you are trying to achieve. We can only point out your error

Related

How to select one record in sql query in java code?

I am getting error in below query as
#Query(value = "SELECT top 1 * from Job where status = 'Success' order by 1 desc")
public Job getLastJob();
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: top near line 1,
I want to select 1st row which has success status order by id desc

I using #Query and Pageable has error: Variables are only allowed when ordering by an expression referencing a column name

I tried to query:
#Query(value = "SELECT * FROM BookingOffice WHERE tripId in (select Trip.tripId from Trip Where Trip.desfination like ?#{#desfination}) ORDER BY ?#{#pageable}",
countQuery = "SELECT COUNT(*) FROM BookingOffice WHERE tripId in (select Trip.tripId from Trip Where Trip.desfination like ?#{#desfination})",
nativeQuery = true)
public Page<BookingOffice> findAllByTrip(String desfination, Pageable pageable);
My PageRequest:
Sort sort = new Sort(Direction.DESC, "officeId");
PageRequest pageRequest = new PageRequest(page, 7, sort);
Hibernate Query on runtime
**> Hibernate:
SELECT
*
FROM
BookingOffice
WHERE
tripId in (
select
Trip.tripId
from
Trip
Where
Trip.desfination like ?
)
ORDER BY
?,
officeId desc offset 0 rows fetch next ? rows only**
ERROR:
May 17, 2020 12:41:29 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/CarPark] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
com.microsoft.sqlserver.jdbc.SQLServerException: The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:254)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1608)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:578)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:508)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7240)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2869)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:243)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:218)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:434)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2171)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1934)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1896)
at org.hibernate.loader.Loader.doQuery(Loader.java:936)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:339)
at org.hibernate.loader.Loader.doList(Loader.java:2693)
at org.hibernate.loader.Loader.doList(Loader.java:2676)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2510)
at org.hibernate.loader.Loader.list(Loader.java:2505)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:2262)
at org.hibernate.internal.AbstractSharedSessionContract.list(AbstractSharedSessionContract.java:1069)
at org.hibernate.query.internal.NativeQueryImpl.doList(NativeQueryImpl.java:173)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1529)
at org.hibernate.query.Query.getResultList(Query.java:165)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) ....
Please help me! Thanks
I think the problem is that you are using Pageable object in order by clause of your select query. It expects a column name for ordering the results.
Please try like below, I have done same kind of implementation in my project and it's working fine.
#Query(value = "SELECT * FROM BookingOffice WHERE tripId in (select Trip.tripId from Trip Where Trip.desfination like %?1%}))",
nativeQuery = true)
public Page<BookingOffice> findAllByTrip(String desfination, Pageable pageable);

"FOR UPDATE NOWAIT", Oracle, springframework, QuerySyntaxException

I'm using implementing the interface that extends from org.springframework.data.repository.CrudRepository and org.springframework.data.jpa.repository.JpaSpecificationExecutor
The problem I hava a query org.springframework.data.jpa.repository.Query with param org.springframework.data.repository.query.Param
I have this Query..
#Query(value = " SELECT c FROM Ctype c WHERE c.code = :code"
+ " FOR UPDATE nowait ")
Ctype findOneByCodeNoWait(
#Param("code") String code);
I have this error:
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract org.company.persistence.entity.Ctype org.company.persist.repository.CtypeRepository.findOneByCodeNoWait(java.lang.String)!
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: FOR near line 1, column 111 [ SELECT c FROM org.company.persistence.entity.Ctype c WHERE c.code = :code FOR UPDATE nowait ]
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: FOR near line 1, column 111 [ SELECT c FROM org.company.persistence.entity.Ctype c WHERE c.code = :code FOR UPDATE nowait ]\"}}"
I was checking another post, but they uses EntityManager...
How solve this?
Try this way:
#Lock(LockModeType.PESSIMISTIC_READ)
#QueryHints(#QueryHint(name = "javax.persistence.lock.timeout",value = "0"))
#Query(value = " SELECT c FROM Ctype c WHERE c.code = :code")
I have tested this with my ongoing project and this code:
#Lock(LockModeType.PESSIMISTIC_READ)
#QueryHints(#QueryHint(name = "javax.persistence.lock.timeout",value = "0"))
#Query("select t from Event t left join fetch t.details ")
List<Event> findAllWithDetails();
`
generates sql like:
SELECT event0_.event_id ...
FROM EVENTS event0_
left outer join event_details details1_
ON event0_.event_id = details1_.event_id
FOR UPDATE NOWAIT

String parameter in Hibernate query

I have changed PK in all tables from int ID to UUID (VARCHAR), but after that this query cannot be executed.
String HQLselect = "from Person person " +
"left join fetch person.researchGroups "+
"left join fetch person.personOptParamVals paramVal "+
"left join fetch paramVal.personOptParamDef paramDef "+
"where person.personId = :id";
Person foundUser = (Person) getHibernateTemplate().findByNamedParam(HQLselect, "id", id);
Error is:
Exception in thread "AWT-EventQueue-0" org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [select person0_.PERSON_ID as PERSON1_32_0_, researchgr1_.RESEARCH_GROUP_ID as RESEARCH1_40_1_, personoptp2_.PERSON_OPT_PARAM_DEF_ID as PERSON1_36_2_, personoptp2_.PERSON_ID as PERSON2_36_2_, personoptp3_.PERSON_OPT_PARAM_DEF_ID as PERSON1_34_3_, person0_.AUTHENTICATION as AUTHENTI2_32_0_, person0_.AUTHORITY as AUTHORITY32_0_, person0_.CONFIRMED as CONFIRMED32_0_, person0_.DATE_OF_BIRTH as DATE5_32_0_, person0_.DEFAULT_GROUP_ID as DEFAULT17_32_0_, person0_.EDUCATION_LEVEL_ID as EDUCATION18_32_0_, person0_.EMAIL as EMAIL32_0_, person0_.FB_UID as FB7_32_0_, person0_.GENDER as GENDER32_0_, person0_.GIVENNAME as GIVENNAME32_0_, person0_.LATERALITY as LATERALITY32_0_, person0_.NOTE as NOTE32_0_, person0_.PASSWORD as PASSWORD32_0_, person0_.PHONE_NUMBER as PHONE13_32_0_, person0_.REGISTRATION_DATE as REGISTR14_32_0_, person0_.SURNAME as SURNAME32_0_, person0_.USERNAME as USERNAME32_0_, researchgr1_.DESCRIPTION as DESCRIPT2_40_1_, researchgr1_.PAID_ACCOUNT as PAID3_40_1_, researchgr1_.OWNER_ID as OWNER5_40_1_, researchgr1_.TITLE as TITLE40_1_, researchgr1_.OWNER_ID as OWNER5_32_0__, researchgr1_.RESEARCH_GROUP_ID as RESEARCH1_0__, personoptp2_.PARAM_VALUE as PARAM3_36_2_, personoptp2_.PERSON_ID as PERSON2_32_1__, personoptp2_.PERSON_OPT_PARAM_DEF_ID as PERSON1_1__, personoptp2_.PERSON_ID as PERSON2_1__, personoptp3_.IS_DEFAULT as IS2_34_3_, personoptp3_.PARAM_DATA_TYPE as PARAM3_34_3_, personoptp3_.PARAM_NAME as PARAM4_34_3_ from PERSON person0_ left outer join RESEARCH_GROUP researchgr1_ on person0_.PERSON_ID=researchgr1_.OWNER_ID left outer join PERSON_OPT_PARAM_VAL personoptp2_ on person0_.PERSON_ID=personoptp2_.PERSON_ID left outer join PERSON_OPT_PARAM_DEF personoptp3_ on personoptp2_.PERSON_OPT_PARAM_DEF_ID=personoptp3_.PERSON_OPT_PARAM_DEF_ID where person0_.PERSON_ID=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
Caused by: ERROR 42818: Comparisons between 'INTEGER' and 'VARCHAR (UCS_BASIC)' are not supported. Types must be comparable. String types must also have matching collation. If collation does not match, a possible solution is to cast operands to force them to the default collation (e.g. SELECT tablename FROM sys.systables WHERE CAST(tablename AS VARCHAR(128)) = 'T1')
I have tried escape ID with ' ', but it didn't change anything. How can I fix it? Thank you.

Syntax Error Hibernate - unexpected token: ON

I've got three tables:
cameras - [id, address, city, url, server_name, …]
vlc - [id, camera_id (which is equal to id in cameras), server_name, port, status]
categories - [id, name]
Hear is my MySQl Syntax, which gave me good result:
"SELECT vlc.camera_id, vlc.url, vlc.port,"
+ " vlc.server_name, cameras.address, cameras.city, categories.name FROM vlc AS vlc" +
" INNER JOIN cameras ON vlc.camera_id = cameras.id" +
" INNER JOIN categories ON cameras.category_id = categories.id"
+ " WHERE vlc.status = 'active' AND ")
But in Hibernate I got this Syntax error:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ON near line 1, column 141
Anyone can help? I know that it may be obvious, but I can not find a solution.
EDIT:
I changed to:
#SuppressWarnings("unchecked")
public List<VLC> getVLCs() {
return getCurrentSession().createSQLQuery("SELECT vlc.camera_id, vlc.url, vlc.port,"
+ " vlc.server_name, cameras.address, cameras.city, categories.name FROM vlc AS vlc" +
" INNER JOIN cameras ON vlc.camera_id = cameras.id" +
" INNER JOIN categories ON cameras.category_id = categories.id"
+ " WHERE vlc.status = 'active'").list();
}
But now I got:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to pl.humandevice.model.VLC
I have to change something in my classes propably
You changed it to native SQL but you are making a projection with attributes from both VLC and camera objects, You need to either restrict the select to VLC objects so Hibernate knows how to map the requested attribute list into VLC objects, or explicitly convert them yourself by receiving a List of OBject[] then selecting each value yourself.
Use createSQLQuery instead createQuery.
Second one is for HQL (Hibernate Query Language) instead of SQL.
UPD:
Using SQL hibernate can't wrap recived data to objects. That's why you have to use HQL.
E.G.:
public List<VLC> getVLCs() {
return getCurrentSession().createQuery("from Cat as cat inner join fetch cat.mate left join fetch cat.kittens").list();
}
Where Cat is Class mapped to table.

Categories