Hibernate return single value query

Query q = session.createQuery("select count(*) from table");
Integer i = (Integer)q.uniqueResult();
 
  That's it, make sure your hql statement only returns one object, otherwise calling uniqueResult() will throw an exception
 
1 The session created by getCurrentSession will be bound to the current thread, while openSession will not.

2 The thread created by getCurrentSession will be closed automatically after transaction rollback or transaction commit, while openSession must be closed manually

Query query = this.getSessionFactory().getCurrentSession().createSQLQuery(sb.toString());
return query.list().size();
 
When the above one throws an exception, you can try the next one:
 
Session session=this.getHibernateTemplate().getSessionFactory().openSession();
return session.createQuery(hql).executeUpdate();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326379645&siteId=291194637