首页 > 代码库 > HQL查询
HQL查询
hibernate中的HQL语句查询,类似于SQL;
1 public class SearchTest { 2 public static void main(String[] args){ 3 Session session = null; 4 Transaction transaction = null; 5 try{ 6 session = HibUtil.getSession(); 7 transaction = session.beginTransaction(); 8 String hql = "from Studentinfo"; 9 Query q = session.createQuery(hql);10 List<Studentinfo> list = q.list();11 for(int i=0; i<list.size();i++){12 Studentinfo stu = list.get(i);13 System.out.println("Name: "+stu.getUsername());14 System.out.println("Phone:"+stu.getUserphone());15 }16 transaction.commit();17 }catch (Exception e) {18 e.printStackTrace();19 }20 21 finally{22 if(session != null ){23 session.close();24 }25 }26 }27 }
其他查询方式:
1 //单个对象 2 String hql = "select count(*) from Studentinfo"; 3 Query q = session.createQuery(hql); 4 Number n = (Number) q.uniqueResult(); 5 6 //Object[]数组 值得到需要的属性 7 String hql = "select s.name,s.phone from Studentinfo s"; 8 List<Object[]> list = q.list(); 9 for(int i=0; i < list.size(); i++){10 Object[] os = list.get(i);11 }12 13 //实体对象14 String hql = "select new Studentinfo(s.name,s.phone) from Student s";15 //......16 17 //where子句参数传递18 //String hql = "from Studentinfo where name = ?";19 String hql = "from Studentinfo where name=:name";//参数名称动态绑定20 Query q = session.createQuery(hql);21 //q.setString(0,"smith");22 q.setString("name", "smith");23 24 //SQL查询25 String sql = "select * from studentinfo where name=:name";26 SQLQuery q = session.createSQLQuery(sql);27 //......28
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。