Java 杂谈重拾Java EEJava学习笔记

重拾Java EE——Hibernate(3)进阶篇(下)

2018-04-09  本文已影响17人  新手村的0级玩家

1 Hibernate的关联关系映射:(多对多)

以Student 与Course为例,是一个经典的多对多的例子

1.1创建实体和映射:

public class Student {
    private Integer sid;
    private String sname;
    // 学生选择多门课程.
    private Set<Course> courses = new HashSet<Course>();
...
}
public class Course {
    private Integer cid;
    private String cname;
    // 课程可以被多个学生选择:
    private Set<Student> students = new HashSet<Student>();
...
}

1.2配置文件

<hibernate-mapping>
    <class name="cn.itcast.demo3.Student" table="student">
        <id name="sid" column="sid">
            <generator class="native"/>
        </id>
        <property name="sname" column="sname"/>
        <!-- 配置多对多关联关系 -->
        <set name="courses" table="stu_cour">
            <key column="sno"/>
            <many-to-many class="cn.itcast. demo3.Course" column="cno"/>
        </set>
    </class>
</hibernate-mapping>
<hibernate-mapping>
    <class name="cn.itcast. demo3.Course" table="course">
        <id name="cid" column="cid">
            <generator class="native"/>
        </id>
        <property name="cname" column="cname"/>
        
        <!-- 配置多对多关联关系映射 -->
        <set name="students" table="stu_cour">
            <key column="cno"/>
            <many-to-many class="cn.itcast. demo3.Student" column="sno"/>
        </set>
    </class>
</hibernate-mapping>

2 抓取策略(优化)

2.1 检索方式

2.2 检查策略

2.3 类级别检索

@Test
public void demo02() {
       //类级别
       Session session = factory.openSession();
       session.beginTransaction();

       //1立即
//      Customer customer = (Customer) session.get(Customer.class, 1);
       //2延迟
       Customer customer = (Customer) session.load(Customer.class, 1);
       
       
       
       //打印
       System.out.println(customer.getCid());
       System.out.println(customer.getCname());

       session.getTransaction().commit();
       session.close();
   }

2.4 关联级别检索

2.4.1 一对多或多对多

2.4.1.1 介绍

2.4.1.2 fetch="join"

@Test
public void demo03() {
       //关联级别:一对多,
       // * Customer.hbm.xml  <set fetch="join">
       // *** select语句使用左外连接,一次性查询所有
       Session session = factory.openSession();
       session.beginTransaction();

       //1 查询客户
       Customer customer = (Customer) session.get(Customer.class, 1);
       System.out.println(customer.getCname());
       
       //2 查询客户订单数
       Set<Order> orderSet = customer.getOrderSet();
       System.out.println(orderSet.size());
       
       //3 查询客户订单详情
       for (Order order : orderSet) {
           System.out.println(order);
       }
       

       session.getTransaction().commit();
       session.close();
   }

2.4.1.3 fetch="select"

2.4.1.4 fetch="subselect"

@Test
public void demo04() {
       //关联级别:一对多,
       // 演示3:* Customer.hbm.xml  <set fetch="subselect">
       Session session = factory.openSession();
       session.beginTransaction();

       //1 查询客户
       List<Customer> allCustomer = session.createQuery("from Customer").list();
       Customer customer = allCustomer.get(0);
       System.out.println(customer.getCname());
       
       //2 查询客户订单数
       Set<Order> orderSet = customer.getOrderSet();
       System.out.println(orderSet.size());
       
       //3 查询客户订单详情
       for (Order order : orderSet) {
           System.out.println(order);
       }
       

       session.getTransaction().commit();
       session.close();
   }

2.4.2 多对一

2.4.2.1 介绍

2.4.2.2 fetch="join"

@Test
public void demo05() {
        //关联级别:多对一,
        // 演示1:* Order.hbm.xml  <set fetch="join">  lazy无效
        // * 注意:检查Customer.hbm.xml 和 Order.hbm.xml 没有额外的配置
        Session session = factory.openSession();
        session.beginTransaction();

        //1 查询订单
        Order order = (Order) session.get(Order.class, 1);
        System.out.println(order.getPrice());
        
        //2 查询订单客户信息
        Customer customer = order.getCustomer();
        System.out.println(customer.getCname());
        

        session.getTransaction().commit();
        session.close();
    }

2.4.2.3 fetch="select"

2.5 批量查询

@Test
   public void demo06() {
       //批量查询
       Session session = factory.openSession();
       session.beginTransaction();
       
       //1 查询所有客户
       List<Customer> allCustomer = session.createQuery("from Customer").list();
       
       //2遍历
       for (Customer customer : allCustomer) {
           System.out.println(customer.getCname());
           System.out.println(customer.getOrderSet().size());
       }
       
       
       session.getTransaction().commit();
       session.close();
   }

2.6 检索总结

3 查询方式总结

1.通过OID检索(查询)

get()立即、如果没有数据返回null
load()延迟,如果没有数据抛异常。

2.导航对象图检索方式:关联查询

customer.getOrderSet()
user.getPost().getDepartment().getDepName();

3.原始sql语句

SQLQuery sqlQuery = session.createSQLQuery("sql 语句")   --->表,表字段(列)
    sqlQuery.list() 查询所有
    sqlQuery.uniqueResult() 查询一个

4.HQL(hibernate query language) hibernate 查询语言

Query query = session.createQuery("hql语句")  --> 对象,对象属性

5.QBC(query by criteria )纯面对对象查询语言

4 HQL【掌握】

4.1 介绍

4.2 查询所有客户

@Test
public void demo01(){
        //1 查询所有
        Session session = factory.openSession();
        session.beginTransaction();
        
        //1  使用简单类名 , 存在自动导包
        // * Customer.hbm.xml <hibernate-mapping auto-import="true">
//      Query query = session.createQuery("from Customer");
        //2 使用全限定类名
        Query query = session.createQuery("from com.itheima.a_init.Customer");
        
        List<Customer> allCustomer = query.list();
        for (Customer customer : allCustomer) {
            System.out.println(customer);
        }
        
        session.getTransaction().commit();
        session.close();
    }

4.3 选择查询

@Test
public void demo02(){
        //2 简单条件查询
        Session session = factory.openSession();
        session.beginTransaction();
        
        
        //1 指定数据,cid OID名称
//      Query query = session.createQuery("from Customer where cid = 1");
        //2 如果使用id,也可以(了解)
//      Query query = session.createQuery("from Customer where id = 1");
        //3 对象别名 ,格式: 类 [as] 别名
//      Query query = session.createQuery("from Customer as c where c.cid = 1");
        //4 查询所有项,mysql--> select * from...
        Query query = session.createQuery("select c from Customer as c where c.cid = 1");
        
        Customer customer = (Customer) query.uniqueResult();
        System.out.println(customer);
        
        session.getTransaction().commit();
        session.close();
    }

4.4 投影查询(部分)

@Test
public void demo04(){
        //4 投影
        Session session = factory.openSession();
        session.beginTransaction();
        
        //1 默认
        //如果单列 ,select c.cname from,需要List<Object>
        //如果多列,select c.cid,c.cname from ,需要List<Object[]>  ,list存放每行,Object[]多列
//      Query query = session.createQuery("select c.cid,c.cname from Customer c");
        //2 将查询部分数据,设置Customer对象中
        // * 格式:new Customer(c.cid,c.cname)
        // * 注意:Customer必须提供相应的构造方法。
        // * 如果投影使用oid,结果脱管态对象。
        Query query = session.createQuery("select new Customer(c.cid,c.cname) from Customer c");
        
        List<Customer> allCustomer = query.list();
        for (Customer customer : allCustomer) {
            System.out.println(customer.getCid() + " : " + customer.getOrderSet().size());
        }
        
        session.getTransaction().commit();
        session.close();
    }

4.5 排序

@Test
public void demo03(){
        //3排序 ,mysql--> select... order by 字段  [asc]|desc ,....
        Session session = factory.openSession();
        session.beginTransaction();
        
        Query query = session.createQuery("from Customer order by cid desc");
        
        List<Customer> allCustomer = query.list();
        for (Customer customer : allCustomer) {
            System.out.println(customer.getCid());
        }
        
        session.getTransaction().commit();
        session.close();
    }

4.6 分页

@Test
public void demo05(){
        //分页
        Session session = factory.openSession();
        session.beginTransaction();
        
        Query query = session.createQuery("from Customer");
        // * 开始索引 , startIndex 算法: startIndex = (pageNum - 1) * pageSize;
        // *** pageNum 当前页(之前的 pageCode)
        query.setFirstResult(0);
        // * 每页显示个数 , pageSize
        query.setMaxResults(2);
        
        List<Customer> allCustomer = query.list();
        for (Customer customer : allCustomer) {
            System.out.println(customer.getCid());
        }
        
        session.getTransaction().commit();
        session.close();
    }

4.7 绑定参数

@Test
public void demo06(){
        /* 6 绑定参数
         * 方式1:占位符,使用? 在hql语句替换具体参数
         *      设置参数 query.setXxx(int , object)
         *          参数1:?位置,从0开始。
         *          参数2:实际参数
         *      例如:String --> query.setString(int,String)
         * 方式2:别名 , 格式 “属性= :别名 ”
         *      设置参数 query.setXxx(String,object)
         *          参数1:别名
         *          参数2:实际参数
         *      例如:Integer --> query.setInteger(String,Integer)
         * 提供公共设置方法
         *  setParameter(int|string , Object)
         */
        Session session = factory.openSession();
        session.beginTransaction();
        
        Integer cid = 1;
        
        //方式1
//      Query query = session.createQuery("from Customer where cid = ?");
//      query.setInteger(0, cid);
        //方式2
        Query query = session.createQuery("from Customer where cid = :xxx");
//      query.setInteger("xxx", cid);
        query.setParameter("xxx", cid);
        
        Customer customer = (Customer) query.uniqueResult();
        System.out.println(customer);
        
        session.getTransaction().commit();
        session.close();
    }

4.8 聚合函数和分组

@Test
public void demo07(){
        /* 7  聚合函数
         */
        Session session = factory.openSession();
        session.beginTransaction();
        
        //1 
//      Query query = session.createQuery("select count(*) from Customer");
        //2 别名
//      Query query = session.createQuery("select count(c) from Customer c");
        //3 oid
        Query query = session.createQuery("select count(cid) from Customer");
        
        Long numLong = (Long) query.uniqueResult();
        int num = numLong.intValue();
        
        System.out.println(num);
        
        
        session.getTransaction().commit();
        session.close();
    }

4.9 连接查询

1.交叉连接 ,等效 sql 笛卡尔积
2.隐式内连接,等效 sql 隐式内连接
3.内连接,等效sql内连接
4.迫切内连接,hibernate底层使用 内连接。
5.左外连接,等效sql左外连接
6.迫切左外连接,hibernate底层使用 左外连接
7.右外连接,等效sql右外连接

内连接和迫切内连接?
左外连接和迫切左外连接?

@Test
public void demo08(){
        /* 8 链接查询 : 左外连接和迫切左外连接?
         * * 左外连接 , left outer join
         *      底层使用sql的左外连接,hibernate进行数据自动封装,将一条记录,封装给两个对象(Customer,Order)
         *      将两个对象添加到一个对象数组中Object[Customer,Order]
         * * 迫切左外链接 left outer join fetch
         *      底层使用sql的左外连接,hibernate将一条记录封装给Customer,讲order数据封装Order,并将order关联到Customer
         *          customer.getOrderSet().add(order)
         *      默认查询的数据重复
         */
        Session session = factory.openSession();
        session.beginTransaction();
        
        //左外连接
//      List list = session.createQuery("from Customer c left outer join c.orderSet ").list();
        //迫切左外链接 (默认数据重复)
//      List list = session.createQuery("from Customer c left outer join fetch c.orderSet ").list();
        //迫切左外链接 (去重复)
        List list = session.createQuery("select distinct c from Customer c left outer join fetch c.orderSet ").list();
        
        
        session.getTransaction().commit();
        session.close();
    }

4.10 命名查询

局部: <class name="" table=""><id><property> <query name="">HQL</class>


@Test
public void demo09(){
       /* 9 命名查询
        */
       Session session = factory.openSession();
       session.beginTransaction();
       
       //全局
       //List list = session.getNamedQuery("findAll").list();
       //局部
       List list = session.getNamedQuery("com.itheima.a_init.Customer.findAll").list();
       
       System.out.println(list.size());
       
       session.getTransaction().commit();
       session.close();
   }

5 QBC【了解】

5.1 QBC查询:

QBC:Query By Criteria条件查询.面向对象的查询的方式.

5.2 QBC简单的查询:

        // 简单查询:
        List<Customer> list = session.createCriteria(Customer.class).list();
        for (Customer customer : list) {
            System.out.println(customer);
        }

5.3 QBC分页的查询:

        Criteria criteria = session.createCriteria(Order.class);
        criteria.setFirstResult(10);
        criteria.setMaxResults(10);
        List<Order> list = criteria.list();

5.4 QBC排序查询:

        Criteria criteria = session.createCriteria(Customer.class);
//      criteria.addOrder(org.hibernate.criterion.Order.asc("age"));
        criteria.addOrder(org.hibernate.criterion.Order.desc("age"));
        List<Customer> list = criteria.list();

5.5 QBC条件查询:

        // 按名称查询:
        /*Criteria criteria = session.createCriteria(Customer.class);
        criteria.add(Restrictions.eq("cname", "tom"));
        List<Customer> list = criteria.list();*/
        
        // 模糊查询;
        /*Criteria criteria = session.createCriteria(Customer.class);
        criteria.add(Restrictions.like("cname", "t%"));
        List<Customer> list = criteria.list();*/
        
        // 条件并列查询
        Criteria criteria = session.createCriteria(Customer.class);
        criteria.add(Restrictions.like("cname", "t%"));
        criteria.add(Restrictions.ge("age", 35));
        List<Customer> list = criteria.list();

5.6 离线查询(了解)

@Test
public void demo10(){
       /* 10 离线查询
        */
       
       //web & service
       DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);
       detachedCriteria.add(Restrictions.eq("cid", 1));
       
       //---------------dao
       
       Session session = factory.openSession();
       session.beginTransaction();
       
       // 离线Criteria 与session绑定
       Criteria criteria = detachedCriteria.getExecutableCriteria(session);
       List<Customer> allCustomer = criteria.list();
       System.out.println(allCustomer.size());
       
       session.getTransaction().commit();
       session.close();
   }

6 常见配置

6.1 整合c3p0(连接池) (了解)

hibernate.c3p0.max_size 2
hibernate.c3p0.min_size 2
hibernate.c3p0.timeout 5000
hibernate.c3p0.max_statements 100
hibernate.c3p0.idle_test_period 3000
hibernate.c3p0.acquire_increment 2
hibernate.c3p0.validate false

6.2 事务

6.2.1 回顾

6.2.2 hibernate设置隔离级别

6.2.3 lost update 丢失更新

6.2.4 hibernate处理丢失更新

@Test
public void demo01(){
        //1 查询所有
        Session session = factory.openSession();
        session.beginTransaction();
        
        Customer customer = (Customer) session.get(Customer.class, 1 ,LockMode.UPGRADE);
        System.out.println(customer);
        
        session.getTransaction().commit();
        session.close();
    }
 ![](https:https://img.haomeiwen.com/i3034232/6823404c2cbc4aa3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

步骤一:

步骤二:

步骤三:测试

@Test
public void demo02(){
        //1 查询所有
        Session session = factory.openSession();
        session.beginTransaction();
        
//      Order order = new Order();
//      order.setPrice(998d);
//      session.save(order);
        
        Order order = (Order) session.get(Order.class, 32);
        order.setPrice(889d);
        
        
        session.getTransaction().commit();
        session.close();
    }
上一篇下一篇

猜你喜欢

热点阅读