码迷,mamicode.com
首页 > Web开发 > 详细

Hibernate之Query接口的uniqueResult()方法

时间:2017-09-03 14:10:33      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:tran   一个   span   返回   多个   hibernate   有一个   out   creat   

如果查询返回多个值用list()方法

 

 1 public void testQuery(){  
 2         Configuration config = new Configuration().configure();  
 3         SessionFactory factory = config.buildSessionFactory(); //创建SessionFactory   
 4         Session session = factory.openSession();        //创建Session   
 5         session.beginTransaction();                     //开始事务   
 6           
 7         Query query = session.createQuery("from Student");  
 8         List list = query.list();  // 用list方法返回多个值   
 9         //List list = session.createQuery("from Student").list();   
10         for(int i=0;i<list.size();i++){  
11             Student student = (Student)list.get(i);  
12             System.out.print(student.getId()+" ");  
13             System.out.print(student.getName()+" ");  
14             System.out.print(student.getSex()+" ");  
15             System.out.print(student.getBirthday());  
16             System.out.println();  
17         }         
18           
19         session.getTransaction().commit();         //提交事务    
20         session.close();                           //关闭Session   
21     } 

 

 

 

 

当确定返回的实例只有一个或者null时 用uniqueResult()方法

 1 public void testGet(){  
 2         Configuration config = new Configuration().configure();  
 3         SessionFactory factory = config.buildSessionFactory();  
 4         Session session = factory.openSession();  
 5         session.beginTransaction();  
 6           
 7         Query query = session.createQuery("from Student s where s.id=?");  
 8         query.setString(0, "2");  
 9         Student student = (Student)query.uniqueResult();  //当确定返回的实例只有一个或者null时 用uniqueResult()方法   
10         //Student student = (Student)session.createQuery("from Student s where s.id=?").setString(0,"5").uniqueResult();   
11           
12         System.out.println(student.getName());  
13         System.out.println(student.getBirthday());  
14           
15       
16         session.getTransaction().commit();  
17         session.close();  
18     }  

 

Hibernate之Query接口的uniqueResult()方法

标签:tran   一个   span   返回   多个   hibernate   有一个   out   creat   

原文地址:http://www.cnblogs.com/slowcity/p/7469360.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!