I have created a query where I want to update some column using an inner query in the same table. And the query working fine in MySQL workbench but if I am using the same query in java then it gives me error like
expecting "set", found 'INNER'
Here is my query which I have created.
UPDATE table1 t1
INNER JOIN (SELECT MAX(time)
FROM table1 WHERE id = 1) t2
ON t1.time = t2.time
SET t1.fromUserId=305,
t1.toUserId=306,
t1.type='Positive',
t1.subcategoryId=508,
t1.isDeleted=false,
t1.isNotify=true;
Java code
@Override
public void methodName(DTOClass dtoClass) throws DatabaseException {
logger.info("*******************In save-update ******************");
StringBuilder saveQuery = new StringBuilder();
try {
saveQuery.append(" UPDATE table1 t1 INNER JOIN (SELECT MAX(time) FROM table1 ");
saveQuery.append(" WHERE id = :addedBy) t2 ON t1.time = t2.time ");
saveQuery.append(" SET t1.fromUserId=:fromUserId, t1.toUserId=:toUserId, t1.type=:type, ");
saveQuery.append( " t1.subcategoryId=:subcategoryId, t1.isDeleted=false, t1.isNotify=:isNotify ");
logger.info(saveQuery.toString());
Query query = getCurrentSession().createQuery(saveQuery.toString());
query.setParameter("addedBy", dtoClass.getAddedBy());
query.setParameter("fromUserId", dtoClass.getFromUserId());
query.setParameter("toUserId", dtoClass.getToUserId());
query.setParameter("type", dtoClass.getType());
query.setParameter("subcategoryId", dtoClass.getSubcategoryId());
query.setParameter("isNotify", dtoClass.getIsNotify());
query.executeUpdate();
} catch (Exception exception) {
logger.error(exception.getMessage(), exception);
throw new DatabaseException(ResourceManager.getProperty(EXCEPTION_DAO_USER));
}
}
Can someone please help. Thanks in advance!
From your code getCurrentSession().createQuery(saveQuery.toString());
I guess you are using some JPA implementation (spring or something? and join in update is not available in JPQL ( https://docs.oracle.com/javaee/6/tutorial/doc/bnbtl.html#bnbud )
So you can either try to send it as a native mysql query. I am not sure what was the exact way to do that because I don't have such project here right now but I believe it was something like: getCurrentSession().createNativeQuery(saveQuery.toString());
Then it should work but it kinds of defeat the purpose of using JPA :)
So I guess you should just rework the query like it was proposed above:
update table1 set fromUserId=305, toUserId=306 where time = (SELECT MAX(time) FROM table1 WHERE id = 1);
Can you try this:
update A
set A.fromUserId=305,
A.toUserId=306,
A.type='Positive',
A.subcategoryId=508,
A.isDeleted=false,
A.isNotify=true
from table1 A
inner join (SELECT MAX(time) as bTime FROM table1 WHERE id = 1) B
on (A.time = (B.bTime))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.