使用HQL语句 随机查询数据库前10条记录
String hql="select top 1 * from EngageExam e where e.majorKindId= '"+majorKindId+"' and e.majorId='"+majorId+"' order by newid()";
我这样写不可以,有没有什么别的方法啊?
...全文
4313打赏收藏
HQL语句随机查询数据
使用HQL语句 随机查询数据库前10条记录 String hql="select top 1 * from EngageExam e where e.majorKindId= '"+majorKindId+"' and e.majorId='"+majorId+"' order by newid()"; 我这样写不可以,有没有什么别的方法啊?
兄弟你真强,怎么可以像你那样写呢?这种写法和写Sql有什么区别吗?既然用了Hibernate为什么不用它里面好的东西呢?
你的Hql可以改写成:
String hql="select * from EngageExam e where e.majorKindId=? and e.majorId=? order by newid";
//创建查询对象
Query query = this.getSession().createQuery(hql);
//对查询语句进行赋值
query.setParameter(0,majorKindId);
query.setParameter(1,majorId);
//设置起始行数和最大查询行数
query.setFirstResult(0);
query.setMaxResults(10);
//返回前10条记录。
return query.list();