package Search.sub; import java.io.File; import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; publicclass Test ...{ publicstaticvoid main(String[] args)...{ String filePath=System.getProperty("user.dir")+File.separator+"src/Search/sub"+File.separator+"hibernate.cfg.xml"; File file=new File(filePath); SessionFactory sessionFactory=new Configuration().configure(file).buildSessionFactory(); Session session=sessionFactory.openSession(); Transaction t=(Transaction)session.beginTransaction(); //查询所有学生年龄都大于11岁的班级对象(结果应为team2) //team1学生年龄是11,13,15,17,19 //team2学生年龄是12,14,16,17,20 /**//* * 使用SQL * select t1.name from testteam t1 where 11<all(SELECT s.age from teststu s where s.team_id=t1.id); */ Query query=session.createQuery("from TestTeam t where 11<all(select s.age from t.students s)"); //注意:不能将11<all 写成all>11以违反Mysql规则 List teamList=query.list(); for (Iterator iterator = teamList.iterator(); iterator.hasNext();) ...{ TestTeam object = (TestTeam) iterator.next(); System.out.println(object.getName()); } //查询有一个学生的年龄为15岁的team对象(结果应为team1) /**//* * 使用SQL * select t1.name from testteam t1 where 15=any(SELECT s.age from teststu s where s.team_id=t1.id); */ Query query1=session.createQuery("from TestTeam t where 15=any(select s.age from t.students s)"); List teamList1=query1.list(); for (Iterator iterator = teamList1.iterator(); iterator.hasNext();) ...{ TestTeam object1 = (TestTeam) iterator.next(); System.out.println(object1.getName()); } t.commit(); } }
运行结果:
Hibernate: select testteam0_.id as id1_, testteam0_.name as name1_ from testteam testteam0_ where 11<all (select students1_.age from teststu students1_ where testteam0_.id=students1_.team_id) team2 Hibernate: select testteam0_.id as id1_, testteam0_.name as name1_ from testteam testteam0_ where 15=any (select students1_.age from teststu students1_ where testteam0_.id=students1_.team_id) team1