An exception occurred while creating a query in EntityManager - java

This is my query.
List exp = entityManager.getEntityManager()
.createQuery("select sum(u.expenseAmount), u.wdExpenseGroup.expenseGroupName from WdExpense u WHERE MONTH(CAST(u.expenseDate as date)) = MONTH(NOW()) AND YEAR(CAST(u.expenseDate as date)) = YEAR(NOW()) group by u.wdExpenseGroup.expenseGroupId")
.getResultList();
I'm getting below error.
java.lang.IllegalArgumentException: An exception occurred while
creating a query in EntityManager: Exception Description: Syntax
error parsing the query [select sum(u.expenseAmount),
u.wdExpenseGroup.expenseGroupName from WdExpense u WHERE
MONTH(CAST(u.expenseDate as date)) = MONTH(NOW()) AND
YEAR(CAST(u.expenseDate as date)) = YEAR(NOW()) group by
u.wdExpenseGroup.expenseGroupId], line 1, column 91: unexpected token
[(]. Internal Exception: NoViableAltException(83!=[661:1:
simpleConditionalExpressionRemainder[Object left] returns [Object
node] : (n= comparisonExpression[left] | (n1= NOT )? n=
conditionWithNotExpression[(n1!=null), left] | IS (n2= NOT )? n=
isExpression[(n2!=null), left] );])
How can I solve this?

MONTH, YEAR, etc are not valid JPQL.
See http://www.datanucleus.org/products/accessplatform_4_0/jpa/jpql.html#JPQL_BNF_Notation

Related

how could I modify the mysql update method?

I want to update mysql table from a dto list, but there is some exception, something like grammer issue, here is my code:
#Override
#Transactional
public void updateCustomCategory(List<ItemDto> itemDtoList) {
if (CollectionUtils.isNotEmpty(itemDtoList)) {
for (ItemDto itemDto : itemDtoList) {
Long l1CustomCategoryId = itemDto.getL1CustomCatId();
Long l2CustomCategoyId = itemDto.getL2CustomCatId();
StringBuilder query =
new StringBuilder(
"update ItemDto item set item.l1CustomCategoryId = :l1CustomCategoryId and item.l2CustomCategoryId = :l2CustomCategoyId where itemId = :itemId");
Query q = this.em.createQuery(query.toString());
q.setParameter("l1CustomCategoryId", l1CustomCategoryId);
q.setParameter("l2CustomCategoyId", l2CustomCategoyId);
q.setParameter("itemId", itemDto.getItemId());
q.executeUpdate();
}
}
}
and exception as below:
2019-10-04 14:49:00.227 ERROR 11909 --- [nio-9092-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: and near line 1, column 108 [update com.shopee.data.dto.brandseller.item.ItemDto item set item.l1CustomCategoryId = :l1CustomCategoryId and item.l2CustomCategoryId = :l2CustomCategoyId where itemId = :itemId]; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: and near line 1, column 108 [update com.shopee.data.dto.brandseller.item.ItemDto item set item.l1CustomCategoryId = :l1CustomCategoryId and item.l2CustomCategoryId = :l2CustomCategoyId where itemId = :itemId]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: and near line 1, column 108 [update com.shopee.data.dto.brandseller.item.ItemDto item set item.l1CustomCategoryId = :l1CustomCategoryId and item.l2CustomCategoryId = :l2CustomCategoyId where itemId = :itemId]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.hql.internal.ast.ErrorTracker.throwQueryException(ErrorTracker.java:93) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:296) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:188) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile
You don't use AND with SET, you separate them with commas. The correct syntax is
SET item.l1CustomCategoryId = :l1CustomCategoryId, item.l2CustomCategoryId = :l2CustomCategoyId

Error on use having with count in querydsl

I trying use querydsl query with having clause with count aggregation but i have the error
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: having near line 4, column 1 [select count(distinct logData.ipAddress)from com.ef.domain.LogData logData where logData.date between ?1 and ?1 having count(logData) >= ?2]
By the following code
return query.select(Projections.constructor(LogData.class, data.count(), data.ipAddress)).from(data).where(data.date.between(args.getStartDate(), args.getFinalDate()))
.groupBy(data.ipAddress).having(data.count().goe(args.getThreshold())).fetchResults().getResults();
What´s wrong?

JPA,JPQL: unexpected token: LEFT near line 1

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

Want to convert and SQL to Hibernate Query Language

I have a requirement where I have to convert an SQL to HQL.
The SQL query is as follows:
select RT.tableNumber, temp.confirmationNumber from ReservationTable RT, (select R.tableNumber, R.confirmationNumber from Reservation R where R.date = 'someDate' and R.time = 'someTime' and R.reservationStatus = 'CONFIRMED') as temp where RT.tableNumber = temp.tableNumber and RT.tableNumber = 'someTableNumber' ;
I tried converting it to the following HQL:
select RT.tableNumber, temp.confirmationNumber from ReservationTable RT, (select R.tableNumber, R.confirmationNumber from Reservation R where R.date = :param1 and R.time = :param2 and R.reservationStatus = 'CONFIRMED') as temp where RT.tableNumber = temp.tableNumber and RT.tableNumber = :param3";
But when I run this HQL through Eclipse, I get the below error lines:
ERROR: line 1:102: unexpected token: (
ERROR: line 1:146: unexpected token: from
SEVERE: Servlet.service() for servlet [dispatcher] in context with
path [/RRSRestApp] threw exception [Request processing failed; nested
exception is org.hibernate.hql.internal.ast.QuerySyntaxException:
unexpected token: ( near line 1, column 102 [select RT.tableNumber,
temp.confirmationNumber from
com.kartik.restaurant.model.ReservationTable RT, (select
R.tableNumber, R.confirmationNumber from
com.kartik.restaurant.model.Reservation R where R.date = :param1 and
R.time = :param2 and R.reservationStatus = 'CONFIRMED') as temp where
RT.tableNumber = temp.tableNumber and RT.tableNumber = :param3; ]]
with root cause org.hibernate.hql.internal.ast.QuerySyntaxException:
unexpected token: ( near line 1, column 102 [select RT.tableNumber,
temp.confirmationNumber from
com.kartik.restaurant.model.ReservationTable RT, (select
R.tableNumber, R.confirmationNumber from
com.kartik.restaurant.model.Reservation R where R.date = :param1 and
R.time = :param2 and R.reservationStatus = 'CONFIRMED') as temp where
RT.tableNumber = temp.tableNumber and RT.tableNumber = :param3; ]
Can anyone help me with this?
According to hibernate documentation HQL subqueries can occur only in the select or where clauses.
for more detail please follow hibernate documentation

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: start near line 1, column 84

I am getting an error while executing the query. The error is:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: start near line 1, column 84 [from com.services.om.entity.OrderLines where orderNumber in (:order_Numbers) start with parentLineIdentifier is null connect by prior orderLineIdentifier = parentLineIdentifier]
My DAO code is :
public List<OrderLineVO> findAllOrders(List<BigDecimal> orderNumbers) throws OrderManagementException {
try{
String getAllOrders = "from OrderLines where orderNumber in (:order_Numbers) order by orderDate desc ";
Query query = em.createQuery(getAllOrders,OrderLines.class);
query.setParameter("order_Numbers", orderNumbers);
List<OrderLines> orderLinesList = query.getResultList();
String queryParentChild = "from OrderLines where orderNumber in (:order_Numbers) start with parentLineIdentifier is null connect by prior orderLineIdentifier = parentLineIdentifier";
Query queryParent = em.createQuery(queryParentChild, OrderLines.class);
queryParent.setParameter("order_Numbers", orderNumbers);
List<OrderLines> orderLinesList2 = queryParent.getResultList();
return OrderLineUTIL.getOrderLines(orderLinesList);
}catch(Exception exception){
logger.error(exception.getMessage());
throw new OrderManagementException(exception.getMessage());
}
}
em.createQuery(queryParentChild, OrderLines.class); // Line is giving above error.
Any Suggestion ?
Also the entity class field variables are marked correctly in query.

Categories