您的位置:首页 > 其它

Hibernate各类概念-如何查询总数

2018-01-31 11:35 453 查看
返回满足条件的总数
查询总数

首先还是准备一个有统计函数的语句
select count(*) from ....
根据这条SQL语句创建一个Query对象,调用Query对象的uniqueResult()方法,返回一个long型的数据,即查询总数。
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class TestHibernate {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();

String name = "iphone";

Query q =s.createQuery("select count(*) from Product p where p.name like ?");
q.setString(0, "%"+name+"%");
long total= (Long) q.uniqueResult();
System.out.println(total);
s.getTransaction().commit();
s.close();
sf.close();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: