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

 

posted @ 2014-07-09 18:48  沽名钓誉  阅读(183)  评论(0编辑  收藏  举报