zoukankan      html  css  js  c++  java
  • 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         
    View Code
  • 相关阅读:
    构建之法阅读笔记02
    4.7-4.13 第八周总结
    构建之法阅读笔记01
    顶会热词统计
    结对作业-四则运算升级版
    3.31-4.5 第七周总结
    大道至简阅读笔记03
    3.23-3.30 第六周总结
    第7周总结
    人月神话阅读笔记之三
  • 原文地址:https://www.cnblogs.com/rememberme/p/hibernateHQL.html
Copyright © 2011-2022 走看看