今天主要将hibernate的HQL查询:
HQL:Hibernate Query Languge
public class TestHQL {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void before(){
Configuration configuration=new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
@After
public void after(){
transaction.commit();
session.close();
sessionFactory.close();
}
@Test
public void testhql(){
//查询所有
// List<Person> persons=session.createQuery("from Person").list();
// for (Person person : persons) {
// System.out.println(person);
// }
//查询某一列
// List<String> names=session.createQuery("select pname from Person").list();
// for (String string : names) {
// System.out.println(string);
// }
//查询某几列 查询结果来源于多张表
// List<Object[]> objects=session.createQuery("select pname,page from Person").list();
// for (Object[] objects2 : objects) {
// String pname=objects2[0].toString();
// int page=Integer.parseInt(objects2[1].toString());
// System.out.println(pname+" "+page);
// }
//构造查询
// List<Person> persons=session.createQuery("select new Person(pname,page) from Person").list();
// for (Person person : persons) {
// System.out.println(person);
// }
//带条件查询
//查询年龄在15 到 60 之间
// List<Person> persons=session.createQuery("from Person where page between ? and ?").setInteger(0, 15).setInteger(1, 60).list();
// List<Person> persons=session.createQuery("from Person where page between :min and :max").setInteger("min", 15).setInteger("max", 60).list();
// for (Person person : persons) {
// System.out.println(person);
// }
//聚合函数
// int page=Integer.parseInt(session.createQuery("select max(page) from Person").uniqueResult().toString());
// System.out.println(page);
//分页
// int pageNo=2;
// int pageSize=2;
// List<Person> persons=session.createQuery("from Person").setFirstResult((pageNo-1)*pageSize).setMaxResults(pageSize).list();
// for (Person person : persons) {
// System.out.println(person);
// }
//排序
//年龄
// List<Person> persons=session.createQuery("from Person order by page desc").list();
// for (Person person : persons) {
// System.out.println(person);
// }
//对象导航
// session.createQuery("from Person p where p.city.caddress like ")
}