[Hibernate] - EAGER and LAZY

Hibernate中的字段映射中的Fetch有兩種方式:EAGER和LAZYhtml

Eager:所有抓取數據庫

Lazy:延遲抓取session

若是在字段中聲明爲Eager,那麼在取得當前Bean時,同時會抓取Bean中的關聯Bean值。即數據庫查詢屢次。反之Lazy則在以後抓取提交查詢。app

 

好比,有以下聲明爲Eager的User Bean:fetch

    @OneToMany(mappedBy="user", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    private Set<UserCard> cards;

此時使用Join查詢時,將會同時把User bean下的cards均一同查詢出來:spa

            // ----------------------------------------------------
            // Left join
            // ----------------------------------------------------
            String hql = "SELECT U FROM User U LEFT JOIN U.cards C WHERE U.userName=:userName AND C.cardID=:cardID";
            Query query = session.createQuery(hql);
            query.setLong("cardID", 1);
            query.setString("userName", "Robin");
            List<User> users = query.list();
            for (User user : users) {
                System.out.println("User ID:" + user.getUserID()
                        + "\tUser name:" + user.getUserName());
            }

輸出的SQL和查詢結果:設計

 

若是把Eager修改成Lazy:code

    @OneToMany(mappedBy="user", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    private Set<UserCard> cards;

查詢:htm

            // ----------------------------------------------------
            // Left join
            // ----------------------------------------------------
            String hql = "SELECT U FROM User U LEFT JOIN U.cards C WHERE U.userName=:userName AND C.cardID=:cardID";
            Query query = session.createQuery(hql); query.setLong("cardID", 1); query.setString("userName", "Robin"); List<User> users = query.list(); for (User user : users) { System.out.println("User ID:" + user.getUserID() + "\tUser name:" + user.getUserName()); }

輸出的SQL和查詢結果:對象


 

 

固然,大多數狀況下,bean的設計都應該爲Lazy

由於若是真要同步查詢獲得關聯對象bean的值,能夠在hql中加入FETCH關鍵字便可完成。

Fetch參考例子:http://www.cnblogs.com/HD/p/3957926.html

使用FETCH,如上查詢hql能夠寫爲:

String hql = "SELECT U FROM User U LEFT FETCH JOIN U.cards C WHERE U.userName=:userName AND C.cardID=:cardID";
相關文章
相關標籤/搜索