大家好,又见面了,我是你们的朋友全栈君。
数据库中根据你的查询条件只会返回唯一结果,就可以用uniqueResult这个方法!否则就用list();其返回类型为Object uniqueResult()方法通常是在业务方法查询语句中用到的,比如(UsersRoles)getSession().createQuery(“select ur from UsersRoles ur where ur.role.id = ? and ur.user.id = ?”) .setParameter(0, roleId) .setParameter(1, userId) .uniqueResult();这时通表示只(从数据库中只返回一条记录)返回一个对象。当不确定时用List()方法
如果查询返回多个值用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 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()方法
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();
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/195193.html原文链接:https://javaforall.cn