当前位置: 首页 > 工具软件 > HibernateD > 使用案例 >

hibernated的HQL查询操作总结

温嘉赐
2023-12-01

只粘贴部分关键代码

1.简单查询

Session session = hibernateUtils.getCurrentSession();
          Transaction transaction =  session.beginTransaction();
          Query query = session.createQuery("from Customer");
          List<Customer> list = query.list();
          for(Customer customer : list) {
             System.out.println(customer);
          }
          transaction.commit();

2.条件查询

Session session = hibernateUtils.getCurrentSession();
              Transaction transaction =  session.beginTransaction();
//            Query query = session.createQuery("from Customer where cust_name = ?");
              Query query = session.createQuery("from Customer where cust_name = ? and cust_source like ?");
              query.setParameter(0, "xxx");
              query.setParameter(1, "a%");
              List<Customer> list = query.list();
              for(Customer customer : list) {
                 System.out.println(customer);
              }
              transaction.commit();

3.投影查询

Session session = hibernateUtils.getCurrentSession();
              Transaction transaction =  session.beginTransaction();
//              Query query = session.createQuery("select c.cust_name from Customer c");
//              Query query = session.createQuery("select c.cust_name,c.cust_source from Customer c");
              Query query = session.createQuery("select new Customer(cust_name,cust_source) from Customer c");
//              List<Object[]> list = query.list();
              List<Customer> list = query.list();
              for(Customer customer : list) {
                 System.out.println(customer);
              }
              transaction.commit();
    

4.分页查询

Session session = hibernateUtils.getCurrentSession();
              Transaction transaction =  session.beginTransaction();          
              Query query = session.createQuery(" from LinkMan");
              query.setFirstResult(10);//从第几条开始查,比如这句话的意思是从第十一条开始查
              query.setMaxResults(5);
              List<LinkMan> list = query.list();
              for(LinkMan man : list) {
                 System.out.println(man);
              }
              transaction.commit();

5.分组统计查询

Session session = hibernateUtils.getCurrentSession();
                  Transaction transaction =  session.beginTransaction();          
                  List<Object[]> list = session.createQuery("select lkm_name,count(*) from LinkMan group by lkm_name").list();
                  for(Object[] objects : list) {
                      System.out.println(Arrays.toString(objects));
                  }
                  transaction.commit();

 

转载于:https://www.cnblogs.com/yanqingguo/p/9757705.html

 类似资料: