无法在休眠状态下执行 select 语句

Cannot execute select statement in hibernate

我有一个操作应该 select 来自 table 的一行,使用 id:

@RequestMapping("/test/{userId}")
@ResponseBody
public void testUserSettings(@DestinationVariable Integer userId){
    System.out.println("test");
    Session session = sessionFactory.openSession();
    Query query = session.createQuery("select us.settings from UserSettings us"
            + " where us.userId = :userId");
    Transaction transaction = null;
    try {
        transaction = session.beginTransaction();
        query.setParameter("userId", userId);
        query.executeUpdate();
        transaction.commit();
    } catch (HibernateException e) {
        if (transaction != null)
            transaction.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
}

它调用该方法,因为打印了 "test"。问题出在声明中。出于某种原因,我在控制台中得到以下输出:

org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for select queries [select us.settings from com.musala.ving.entities.UserSettings us where us.userId = :userId]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.errorIfSelect(QueryTranslatorImpl.java:324)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:444)
at org.hibernate.engine.query.spi.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:379)
at org.hibernate.internal.SessionImpl.executeUpdate(SessionImpl.java:1286)
at org.hibernate.internal.QueryImpl.executeUpdate(QueryImpl.java:118)
at com.musala.ving.controllers.UserSettingsController.testUserSettings(UserSettingsController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

query.executeUpdate();

您更新了 select 查询!? 错误消息是怎么说的... "Not supported for select queries" 使用 query.execute();或者正确的方法是什么...

您正在呼叫 query.executeUpdate(); 进行 select 查询。尝试使用 query.list()query.uniqueResult()

如果您希望获得单个结果,则应使用

query.uniqueResult()

Query#list() 的 Javadoc 摘录:

Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[].

Query#uniqueResult() 的 Javadoc 摘录:

Convenience method to return a single instance that matches the query, or null if the query returns no results.

此外,transaction.commit(); 应该不是必需的,因为此查询不会更新数据库。

@RequestMapping("/test/{userId}")
@ResponseBody
public void testUserSettings(@DestinationVariable Integer userId){
    System.out.println("test");
    Session session = sessionFactory.openSession();
    Query query = session.createQuery("select us.settings from UserSettings us"
            + " where us.userId = :userId");
    Transaction transaction = null;
    try {
        transaction = session.beginTransaction();
        query.setParameter("userId", userId);
        query.list(); 
        transaction.commit();
    } catch (HibernateException e) {
        if (transaction != null)
            transaction.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
}

我将 hibernate 与 hql 结合使用(与 spring mvc 结合使用,如果这很重要)并通过执行以下操作解决了问题:

String hql = "select clientId from Cart where cartId = :val" ;
        Query query = getSession().createQuery(hql);
        query.setParameter("val", cartId);
        //int result = query.executeUpdate(); OLD VERSION. REPLACED WITH THE LINE BELOW:
        int result = query.getFirstResult();
        return result;

所以对我来说 getFirstResult() 解决了问题。