需求
需要select某个表,随机获取多条记录
实现
利用rand()函数,hibernate会根据数据库不同(例如spring.jpa.properties.dialect,MySQL是org.hibernate.dialect.MySQLDialect,Oracle是org.hibernate.dialect.Oracle10gDialect),生成相应数据库的SQL
/**
* 返回随机选择的size个记录
*/
public List<Student> listStudents(int size) {
String hql = "from Student t where 1=1 order by rand()";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.setMaxResults(size).list();
}
文章评论