hibernate uniqueResult方法
假设查询返回多个值用list()方法
- 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
- }
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()方法
- public void testGet(){
- Configuration config = new Configuration().configure();
- SessionFactory factory = config.buildSessionFactory();
- Session session = factory.openSession();
- session.beginTransaction();
- Query query = session.createQuery("from Student s where s.id=?");
- query.setString(0, "2");
- Student student = (Student)query.uniqueResult(); //当确定返回的实例仅仅有一个或者null时 用uniqueResult()方法
- //Student student = (Student)session.createQuery("from Student s where s.id=?").setString(0,"5").uniqueResult();
- System.out.println(student.getName());
- System.out.println(student.getBirthday());
- session.getTransaction().commit();
- session.close();
- }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。