hibernate hql语句实现随机抽取10条数据库数据

hibernate hql语句实现随机抽取10条数据库数据请各位指教怎么写
2024-11-24 18:16:26
推荐回答(1个)
回答1:

public void randResultSet() {
HashSet set = new HashSet();
SessionFactory sf = HibernateSessionFactory.getSessionFactory();
Session s = sf.openSession();
List list = s.createQuery("from user").list();
int maxSize = list.size();
while (true) {
int randNumber = (int) (Math.random() * maxSize + 1) - 1;
set.add(randNumber);
if (set.size() >= 10) {
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int a : set) {
user u = (user) list.get(a);
System.out.println(u.getName());
}

}