hibernate uniqueResult方法

时间:2023-12-24 21:36:31

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

当确定返回的实例仅仅有一个或者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. Query query = session.createQuery("from Student s where s.id=?");
  7. query.setString(0, "2");
  8. Student student = (Student)query.uniqueResult();  //当确定返回的实例仅仅有一个或者null时 用uniqueResult()方法
  9. //Student student = (Student)session.createQuery("from Student s where s.id=?").setString(0,"5").uniqueResult();
  10. System.out.println(student.getName());
  11. System.out.println(student.getBirthday());
  12. session.getTransaction().commit();
  13. session.close();
  14. }