Hibernate:HQL、QBC和SQL查询

(一)HQL(Hibernate Query Language)查询方式:

文中Customer、LinkMan为客户和联系人类,需做好映射。

    1)别名查询:

Query query = session.createQuery("from Customer c:);

List list = query.list();

    2)排序查询

List list  = sessioni.createQuery("from Customer order by cust_id desc").list();

    3)条件查询

多属性查询:

Query query = session.createQuery("from Customer where cust_source = ? and cust_name like = ?");

query.setParameter(0,"XXX");

query.setParameter(1,"Y%");

按名称查询:

Query query = session.createQuery("from Customer where cust_source =:aaa  and cust_name like :bbb");

query.setParameter("aaa","XXX");

query.setParameter("aaa","Y%");

    4)投影查询:查询对象的某个或某些属性

多属性查询:

List list = session.createQuery("select c.cust_name,c.source from Customer c").list();

将查询的属性封装到对象中:

List list = session.createQuery("select new Customer(cust_name,source) from Customer c").list();

    5)分页查询:

Query query = session.createQuery("from Customer");

query.setFirstResult(20);

query.setMaxResults(10);

    6)分组统计查询:

List list = session.createQuery("select cust_source,count(*) from Customer group by cust_source).list();

    7)HQL的多表查询

A;内连接:a:显示内连接;   b:隐式内连接; c:迫切内连接

B:外连接:a:左外连接;   b:右外连接;   c:迫切左外连接

迫切内连接:就是在普通的内连接inner join后加一个关键字fetch。普通内连接是以Object数组方式进行存储,而迫切内连接是以对象的方式进行存储。

List list = session.createQuery("select distinct c from Customer c inner join fetch c.linkMans”).list(); //他会通知Hibernate,将另一个对象的数据封装到该对象中。

(二)QBC(Query By Criteria)查询方式:

   Query By Criteria:条件查询, 它是一种更加面向对象化的查询方式。

    1)排序查询:

       Criteria criteria = session.createCriteria(Customer.class);   //获得Criteria对象

       criteria.addOrder(Order.desc("cust_id"));

       List list = criteria.list();

    2) 分页查询:

       criteria.setFirstResult(10);

       criteria.setMaxResult(20);

    3)条件查询:

       criteria.add(Restrictions.eq("cust_source","开发部"));

       criteria.add(Restrictions.like("cust_name","李%));

    4)统计查询  (setProjection:聚合函数和group by having)

       criteria.setProjection(Projections.rowCount));

       Long num = (Long) criteria.uniqueResult();

    5)离线条件查询  ---DetachedCriteria

       DetachedCriteria dc = DetachedCriteria.forClass(Customer.class);

       dc.add(Restrictions.like("cust_name","李%");

       Criteria criteria  = dc.getExecutableCriteria(session);

       List list = criteria.list();

(三)QBC(Query By Criteria)查询方式:

    SQL查询创建:

A:存到数组中:

        SQLQuery sqlQuery = session.createQuery("select * from 表名");

        List list = sqlQuery.list();

B:封装到对象中

       SQLQuery sqlQuery = session.createQuery("select * from 表名");

       sqlQuery.addEntity(Customer.class);  //封装到对象中

    SQL多表查询

A.内连接:隐式内连接:select * from A,B where A.id = B.id;

                  显示内连接:select * from A inner join B on A.id = B.id;

B.外连接:左外连接:select * from A left outer join B on A.id = B.id;

                  右外连接:select * from A right outer join B on A.id = B.id;

你可能感兴趣的:(Hibernate:HQL、QBC和SQL查询)