简体   繁体   中英

Using hibernate return wrong count value of a query

I'm trying to check if there is an username in a database that is equal to the passed String. This is the method.

public  boolean alredyTakenUsername(String userna) {
   int numb = 0;
   s = sessionFactory.openSession();
   try {
       String sql = "SELECT COUNT(*) FROM User where User.username= :usern";
       Query query = s.createQuery(sql);
       query.setParameter("usern",userna);
       numb = ((Number)query.getSingleResult()).intValue();
       if (numb == 1)
           return true;
       else
           return false;
   }catch (Exception e){
       e.printStackTrace();
   } finally {
       s.close();
   }
   return false;
}

I put in the database the username and with the query:

select count(*) from User where username='fabio'

TABLE:

USER( username CHAR(20),
      pass CHAR(40),
      loggedstatus BOOLEAN,
      PRIMARY KEY(username));

It returns 1 that is correct. But the method always return 0 when i use userna=fabio . I can't use uniqueResult() because Hibernate5 doesn't allow it. Why?

I solved the problem like this:

public  boolean alredyTakenUsername(String userna) {
   s = sessionFactory.openSession();

   try {
       String sql = "SELECT COUNT(*) FROM User where User.username= :usern";
       NativeQuery sqlQuery = s.createSQLQuery(sql);
       sqlQuery.setParameter("usern",userna);
       int numb = ((Number)sqlQuery.getSingleResult()).intValue();
       if (numb == 1)
           return true;
       else
           return false;
   } catch (Exception e){
       e.printStackTrace();
   } finally {
       s.close();
   }
   return false;
}

I think that the mistake was due at the use of the class Query that is specific for a query of Hibernate. NativeQuery admit query of the dialect, in my case SQL (like the method that i use)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM