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
Related
#Query(value = "DECLARE #StartDateTime DATETIME = DATEADD(hour,-1,GETUTCDATE()) EXEC [Fetch].[mevisio_downtimedata] " +
"#StartDateTime = :startDateTime," +
"#workCenterList = :workCenterList",nativeQuery = true)
List<DownTimeData> retriveOneHrDowntime(#Param("startDateTime") LocalDateTime startDateTime, #Param("workCenterList") List<String> workCenterList);
Getting Error:
2021-05-06 00:26:04.506 ERROR 14840 --- [ scheduling-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Incorrect syntax near '('.
2021-05-06 00:26:04.513 ERROR 14840 --- [ scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
You cannot execute stored procedures with a #Query
You have to define a NamedStoredProcedureQuery on an entity
#Entity
#NamedStoredProcedureQuery(name = "User.plus1", procedureName = "plus1inout", parameters = {
#StoredProcedureParameter(mode = ParameterMode.IN, name = "arg", type = Integer.class),
#StoredProcedureParameter(mode = ParameterMode.OUT, name = "res", type = Integer.class) })
public class User {}
And then you can use #Procedure to execute it
#Procedure
Integer plus1inout(#Param("arg") Integer arg);
Please read the documentation:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.stored-procedures
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
I am trying to batch delete data from table . For that am setting parameter list for deletion.
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
ids.add(4);
Session session1 = sfactory.openSession();
Transaction txn1 = session1.beginTransaction();
Query query = session1.createQuery("delete from QueueData tbl where tbl.iID in =:id");
query.setParameter("id", ids);
int i = query.executeUpdate();
txn1.commit();
I am getting exception while executing statement.
SEVERE: line 1:61: unexpected token: =
Exception in thread "main"
org.hibernate.hql.ast.QuerySyntaxException:
unexpected token: = near line 1, column 61 [delete from
hibernetexamples.QueueData tbl where tbl.iID in =:id]
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:31)
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:24)
at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:59)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:258)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:157)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623)
at hibernetexamples.HibernetExamples.main(HibernetExamples.java:104)
You should be aware of basic sql.
IN condition syntax
Your delete query should look like:
"delete from QueueData tbl where tbl.iID in (:id)"
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
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.