使用createSQLQuery时,Spring getSingleResult()和getResultList()异常

时间:2018-04-05 14:52:41

标签: java spring spring-mvc

我有这个代码,我用来登录移动设备用户,并且这样做我正在检查一些用户输入,并希望查询表是否存在字符串。我希望getSingleResult()出现问题,但getResultList出现问题。

这是代码

//Mobile Login
        @ResponseBody
        @RequestMapping(value = { "/mobileloginbackend" }, method = RequestMethod.POST)
        public String mobilelogin(@RequestParam String ssoId,@RequestParam String password) {

        Session currentSession = sessionFactory.getCurrentSession();
        @SuppressWarnings("rawtypes")
        Query theQuery = currentSession.createSQLQuery("select password from accounts where sso_id=:name");
        theQuery.setParameter("name", ssoId);
        List list = theQuery.getResultList();
        String stored_password = list.get(0).toString();

        if(list.isEmpty()){
            return "that user does not exist";
        }

        if(list.size() == 0){
        return "that user does not exist";  
        }

        if(passwordEncoder.matches(password,stored_password)){
            return "successful login";
        }
        else{
            return "wrong credentials";
        }

        }

这两行是提供异常的行

if(list.isEmpty()){
            return "that user does not exist";
        }

        if(list.size() == 0){
        return "that user does not exist";  
        }

我收到错误500(内部服务器错误)。

我怎样才能做到这一点?。

2 个答案:

答案 0 :(得分:0)

如果你的名单确实是空的,你是否从这一行得到ArrayIndexOutOfBoundsException

String stored_password = list.get(0).toString();

在尝试获取第一个元素之前,您应首先检查它是否为空。

顺便说一下,if(list.isEmpty())if(list.size() == 0)完全相同。

答案 1 :(得分:0)

这最终对我有用

        //Mobile Login
        //import javax.persistence.NoResultException;
        @ResponseBody
        @RequestMapping(value = { "/mobileloginbackend" }, method = RequestMethod.POST)
        public String mobilelogin(@RequestParam String ssoId,@RequestParam String password) {

        try {
        Session currentSession = sessionFactory.getCurrentSession();
        @SuppressWarnings("rawtypes")
        Query theQuery = currentSession.createSQLQuery("select password from accounts where sso_id=:name");
        theQuery.setParameter("name", ssoId);
        String stored_password = theQuery.getSingleResult().toString();
        if(passwordEncoder.matches(password,stored_password)){
            return "successful login";
        }
        else{
            return "wrong credentials";
        }
          }
       catch (NoResultException e) { 
         return "That user does not exist.";
         }

        }