Want to convert and SQL to Hibernate Query Language - java

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

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

"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

org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: Exception

after updating of hibernate and spring a get the following error for this query:
#NamedQuery(name = "Payment.byAmount",
query = "select p from Payment as p join p.application as a where p.amount = ?1 and p.channel = ?2 and p.type =?3 and p.created = ?4 and p.deletedDate is null and a.uuid = ?5")
Error:
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'a.id' [select count(p) from de.model.Payment p join p.application a1 where p.type = .....
Any ideas how this can be solved?
Thanks in advance.

The field in this expression has an invalid table in this context

i'm trying to do following query:
#NamedQuery(name="Grade.findGradeByClassGroup",
query= "SELECT gr From Grades gr join DeterminateTable d on gr.DeterminateTableId = d.DeterminateTableId join SchoolYears sy on gr.GradeId = sy.GradeId join ClassGroups cg on cg.schoolYear = sy.YearInt where cg.groupId = :classGroup")
And I get this exception:
Caused by: Exception [EclipseLink-6069] (Eclipse Persistence Services - 2.6.0.v20141202-3914740): org.eclipse.persistence.exceptions.QueryException
Exception Description: The field [Grades.GradeId] in this expression has an invalid table in this context.
Query: ReadAllQuery(name="Grade.findGradeByClassGroup" referenceClass=Grade jpql="SELECT gr From Grades gr join DeterminateTable d on gr.DeterminateTableId = d.DeterminateTableId join SchoolYears sy on gr.GradeId = sy.GradeId join ClassGroups cg on cg.schoolYear = sy.YearInt where cg.groupId = :classGroup")
at org.eclipse.persistence.exceptions.QueryException.invalidTableForFieldInExpression(QueryException.java:755)
at org.eclipse.persistence.internal.expressions.FieldExpression.validateNode(FieldExpression.java:325)
at org.eclipse.persistence.expressions.Expression.normalize(Expression.java:3291)
at org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:369)
at org.eclipse.persistence.internal.expressions.FieldExpression.normalize(FieldExpression.java:225)
at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:224)
at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:574)
at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:865)
at org.eclipse.persistence.expressions.ExpressionBuilder.normalize(ExpressionBuilder.java:267)
at org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:363)
at org.eclipse.persistence.internal.expressions.FieldExpression.normalize(FieldExpression.java:225)
at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:232)
at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:574)
at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:865)
at org.eclipse.persistence.expressions.ExpressionBuilder.normalize(ExpressionBuilder.java:267)
at org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:363)
at org.eclipse.persistence.internal.expressions.QueryKeyExpression.normalize(QueryKeyExpression.java:758)
at org.eclipse.persistence.internal.expressions.QueryKeyExpression.normalize(QueryKeyExpression.java:671)
at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:224)
at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:574)
at org.eclipse.persistence.internal.expressions.SQLSelectStatement.normalize(SQLSelectStatement.java:1474)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.buildNormalSelectStatement(ExpressionQueryMechanism.java:550)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.prepareSelectAllRows(ExpressionQueryMechanism.java:1722)
at org.eclipse.persistence.queries.ReadAllQuery.prepareSelectAllRows(ReadAllQuery.java:867)
at org.eclipse.persistence.queries.ReadAllQuery.prepare(ReadAllQuery.java:798)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:666)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:909)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:615)
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:342)
... 65 more
I can't figure out whats wrong, tried to google but couldn't get any answers...
What could be causing this?

An exception occurred while creating a query in EntityManager

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

Categories