12月27日笔记

时间:2022-02-24 13:44:49


连接分为内连接、外连接和全连接

外连接分为:左外连接、右连接

内连接又叫自然连接

createQuery()的括号里面不能写select  *   .

mySQL不支持full join

 

inner join(等值连接):只返回两个表中连结字段相等的行

left join(左连接):返回包括左表中的所有记录和右表中连结字段相等的记录

A表 left join B表  左连  以A表位基础,A表的全部数据,B表有的组合,没有的为null

right join(右连接):返回包括右表的所有记录和左表中连结字段相等的记录

A表 right join B表  右连  以B表位基础,B表的全部数据,A表有的组合,没有的为null

 

 

select c.*,o.* from customers c,orders owhere c.id=o.cid全连接

 

select c.*,o.* from customers c INNER joinorders o on c.id=o.cid等值内连接

 

select c.*,o.* from customers c LEFT joinorders o on c.id=o.cid左外连接

 

    //连接查询

    //内连接

    @Test

    public void join2(){

       Session session=HibernateUtil.getSession();

       //  select c.id,c.realName,o.id,o.number fromCustomers as c left join c.orders as o where c.id=1

       List<Object[]> customer=session.createQuery("select c.id,c.realName,o.id,o.number from Customersas c left join c.orders as o where c.id=1").list();

       for(Object[] c:customer){

           System.out.println(c[0]+"----"+c[1]);

       }

    }

运行后结果:

Hibernate: selectcustomers0_.id as col_0_0_, customers0_.realName as col_1_0_, orders1_.id ascol_2_0_, orders1_.number as col_3_0_ from pros.customers customers0_ leftouter join pros.Orders orders1_ on customers0_.id=orders1_.cid wherecustomers0_.id=1

1----435

 

//Criteria方法查询

    @Test

    public void join3(){

       Session session=HibernateUtil.getSession();

       /*Criteria criteria=session.createCriteria(Customers.class).add(Restrictions.like("realName","%a%"));//返回的是Criteria对象

       List<Customers> customers=criteria.list();*/

       List<Customers> customers=session.createCriteria(Customers.class)

                            .add(Restrictions.like("realName", "%a%"))

                            .createCriteria("orders")

                            .add(Restrictions.like("number", "%223%"))

                            .list();//链式查询

   

       for(Customers c:customers){

           System.out.println(c.getEmail());

       }

    }

   

  //标量查询

    @Test

    public void join4(){

       Session session=HibernateUtil.getSession();

       //session.createSQLQuery("select* from customers").list();默认返回的是数组

       List<Customers> customers=session.createSQLQuery("select * from customers").addEntity(Customers.class).list();//加了.addEntity(Customers.class),返回的就不是数组而是实体对象了

   

       for(Customers c:customers){

           System.out.println(c.getEmail());

       }

    }