hibernate中HQL查询补充(联合查询,inner join,left outer join,子查询的使用)

package com.shiryu.otm;

imp ort java.util.Iterator;

imp ort org.hibernate.Session;
imp ort org.hibernate.SessionFactory;
imp ort org.hibernate.Transaction;
imp ort org.hibernate.cfg.Configuration;

//hql 的联合查询
public class HqlTest {
    public static void main(String[] args) {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

        // 1.Inner Join 返回所有满足关联条件的记录组合
        // 使用fetch关键字表明Address对象属性读出后立即填充到对应的User对象(addresses集合属性)中
        // 如果不使用fetch 结果集中,每个条目都是一个Object数组
        Session session = sessionFactory.openSession();

        String hql = "from User user inner join fetch user.addresses";

        Iterator it = session.createQuery(hql).list().iterator();
        while (it.hasNext()) {
            User user = (User) it.next();
            System.out.println(user.getId() + " " + user.getName() + " " + user.getAddresses());
        }
        session.close();

        // 2.Left outer join
        // 返回User表中所有的记录(hql中位于左侧的表),及其对应的地址信息,如果没有则用null代替
        Session session1 = sessionFactory.openSession();
        Transaction tr1 = session1.beginTransaction();

        String hql2 = "from User user left join fetch user.addresses";

        Iterator it2 = session1.createQuery(hql2).list().iterator();
        while (it2.hasNext()) {
            User user = (User) it2.next();
            System.out.println(user.getId() + " " + user.getName() + " " + user.getAddresses());
        }
        session1.close();
        // right outer join 则与left相反 fetch 对其无效
        // full join 是left outer join和right outer join的并集

        // 4.6.8子查询的使用
        Session session2 = sessionFactory.openSession();
        Transaction tr2 = session2.beginTransaction();

        String hql3 = "from User user where (select count(*) from user.addresses)>1";

        Iterator it3 = session2.createQuery(hql3).list().iterator();
        while (it3.hasNext()) {
            User user = (User) it3.next();
            System.out.println(user.getId() + " " + user.getName());
        }
        session2.close();

        // hibernate 也提供sql查询方式(有问题?)
        Session session3 = sessionFactory.openSession();
        Transaction tr3 = session3.beginTransaction();

        String sql = "select {user.*} from User as user";

        Iterator it4 = session3.createSQLQuery(sql).list().iterator();
        while (it4.hasNext()) {
            User user = (User) it4.next();
            System.out.println(user.getId() + " " + user.getName());
        }
    }

}

你可能感兴趣的:(JOIN,JOIN,inner,left,outer,hibernate中联合查询,子查询的使用)