无法在hibernate中执行select语句

时间:2015-02-27 11:43:32

标签: java spring hibernate hql

我有一个操作应该使用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)

4 个答案:

答案 0 :(得分:9)

您正在调用query.executeUpdate();查询select。请尝试使用query.list()query.uniqueResult()

如果您期望单个结果,则应使用

query.uniqueResult()

Javadoc摘录Query#list()

  

将查询结果作为List返回。如果查询在前一行包含多个结果,则结果将在Object []的实例中返回。

Javadoc摘录Query#uniqueResult()

  

返回与查询匹配的单个实例的便捷方法,如果查询未返回任何结果,则返回null。

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我正在将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()解决了这个问题。

答案 3 :(得分:-2)

  

query.executeUpdate();

你做了一个选择查询的更新! 错误消息如何显示..."不支持选择查询" 使用query.execute();或者正确的方法是什么......