更新在mysql工作台中工作但不在java代码中工作的查询

bvk5enib  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(455)

我已经创建了一个查询,希望在其中使用同一个表中的内部查询更新某个列。查询在mysql工作台中运行良好,但是如果我在java中使用相同的查询,那么它会给我类似错误的消息

expecting "set", found 'INNER'

这是我创建的查询。

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代码

@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));

        }

    }

有人能帮忙吗。提前谢谢!

s3fp2yjn

s3fp2yjn1#

你能试试这个吗:

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))
krugob8w

krugob8w2#

从你的代码 getCurrentSession().createQuery(saveQuery.toString()); 我猜您正在使用一些jpa实现(spring还是什么?而join-in更新在jpql中不可用(https://docs.oracle.com/javaee/6/tutorial/doc/bnbtl.html#bnbud)
因此,您可以尝试将其作为本机mysql查询发送。我不知道确切的方法是什么,因为我现在没有这样的项目,但我相信它是这样的: getCurrentSession().createNativeQuery(saveQuery.toString()); 那么它应该可以工作,但是它有点违背了使用jpa的目的:)
所以我想你应该像上面建议的那样重新修改查询:

update table1 set fromUserId=305, toUserId=306 where time = (SELECT MAX(time)  FROM table1 WHERE id = 1);

相关问题