对于我们学习的hql,我大概理解为就是一种查询的语言,它没有增加、删除、修改的作用,而对我们用来查询的操作,感觉用起来就是很简便,代码很少,很好理解一些。
下面是查询操作的简单实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
package com.lc.view; import java.util.iterator; import java.util.list; import org.hibernate.session; import org.hibernate.transaction; import com.lc.domain.student; import com.lc.utils.hibernateutil; public class selectstudent { public static void main(string[] args) { selectsomestudents(); } /** * 1.检索所有的学生 **/ public static void selectallstudents(){ session session = null ; transaction ts = null ; try { session = hibernateutil.getcurrentsession(); ts = session.begintransaction(); list<student> list = session.createquery( "from student" ).list(); //取出数据1.for循环增强 for (student stu:list){ system.out.println(stu.getsid()+ " " + stu.getsname()+ " " +stu.getsdept()); } //取出数据2.迭代器 system.out.println( "------------------------------" ); iterator iterator = list.iterator(); while (iterator.hasnext()){ student s = (student) iterator.next(); system.out.println(s.getsid()+ " " + s.getsname()+ " " +s.getsdept()); } ts.commit(); } catch (exception e) { if (ts != null ) { ts.rollback(); } throw new runtimeexception(e.getmessage()); } finally { if (session != null && session.isopen()) { session.close(); } } } /** * 2.检索部分的学生 **/ public static void selectsomestudents(){ session session = null ; transaction ts = null ; try { session = hibernateutil.getcurrentsession(); ts = session.begintransaction(); /** *不可以这样去除数据了 因为只有student对象的两个属性值 不是一个对象 list<student> list = session.createquery("select sname,sdept from student").list(); for(student stu:list){ system.out.println(stu.getsname()+" "+stu.getsdept()); }**/ list list = session.createquery( "select sname,sdept from student" ).list(); for ( int i= 0 ;i<list.size();i++){ object[] obj = (object[]) list.get(i); system.out.println(obj[ 0 ].tostring()+ " " +obj[ 1 ].tostring()); } ts.commit(); } catch (exception e) { if (ts != null ) { ts.rollback(); } throw new runtimeexception(e.getmessage()); } finally { if (session != null && session.isopen()) { session.close(); } } } } |
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/xlgen157387/article/details/39804385
查看更多关于Hibernate中使用HQLQuery查询全部数据和部分数据的方法实例的详细内容...