You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Hibernate中Update查询的createQuery方法弃用问题?

修复Hibernate 6中Update查询的弃用警告问题

在Hibernate 6中,用createQuery执行UPDATE/DELETE这类DML语句会触发弃用警告——因为新版本把数据检索(SELECT)和数据变更(UPDATE/DELETE)的API做了明确拆分,推荐用专门的createMutationQuery处理数据变更操作。

具体修复步骤:

  • 把session.createQuery替换为session.createMutationQuery,该方法是Hibernate 6专为DML操作提供的API
  • 用MutationQuery类型替代原有的Query类型,适配新API的类型规范

修改后的完整代码:

import org.hibernate.MutationQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.sql.Timestamp;

public static int setLastIpTimeStamp(Timestamp ipLastTimeStamp) {
    int rowsaffected = -1;
    try (Session session = SessionFactoryManager.getSessionFactory().openSession()) {
        Transaction tx = session.beginTransaction();
        try {
            MutationQuery query = session.createMutationQuery("UPDATE HistoryDataProcessorSettingsEntity row SET row.ipLastTimeStamp=:ipLastTimeStamp WHERE row.id=:id ")
                    .setParameter("id", 1)
                    .setParameter("ipLastTimeStamp", ipLastTimeStamp.toInstant());
            rowsaffected = query.executeUpdate();
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
            if (Logger.isErrorEnabled())
                Logger.error(e);
        }
    } catch (Exception e) {
        if (Logger.isErrorEnabled())
            Logger.error(e);
    }
    return rowsaffected;
}

补充说明:

MutationQuery是Query的子类,专门用于DML操作,语义更清晰,完全符合Hibernate 6的API设计逻辑。如果需要更严格的类型校验,也可以使用createMutationQuery的泛型重载(比如泛型参数设为Void),但上述写法已经足够解决弃用警告问题。

内容的提问来源于stack exchange,提问作者Ram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 23:45:03