简体   繁体   中英

JPA auto loaded lazy collection

I have two entity with relationship following:

public class Category implements Serializable {
     @Column(name = "caID")
     private Integer caID;
     @OneToMany(cascade=CascadeType.ALL,mappedBy="caID",fetch=FetchType.LAZY)
     private List<Product> productList;
     //..... GET and SET        
}
public class Product implements Serializable {
     @Column(name = "pID")
     private Integer pID;
     @JoinColumn(name = "caID", referencedColumnName = "caID")
     @ManyToOne(optional = false, fetch = FetchType.EAGER)
     private Category caID;
     //..... GET and SET        
}

Category Model:

private List<Category> findCategoryEntities(boolean all, int maxResults, int firstResult) {
    EntityManagerFactory eMF = null;
    EntityManager eM = null;
    try {
        eMF = getEntityManagerFactory();
        eM = getEntityManager(eMF);
        Query q=eM.createQuery("SELECT ca FROM Category ca");
        //Or using Criteria
        //CriteriaQuery cq = eM.getCriteriaBuilder().createQuery();
        //cq.select(cq.from(Category.class));
        //Query q = eM.createQuery(cq);
        if (!all) {
            q.setMaxResults(maxResults);
            q.setFirstResult(firstResult);
        }
        return q.getResultList();
    } finally {
        closeConnection(eM, eMF);
    }
}

I think if I set fetch loading of listProduct is lazy type, this property won't auto loaded by Entity Manager. But when I call method 'findCategoryEntities' and check productList, it's not null? After I use Criteria and I still get the same result. How can I get all Category but not auto initialize productList? And How can I set productList after that but not initialize Category again?

When you mark a child as lazy, and load the parent, the child list will never be null. It will return you proxy to the list of child objects. So when you do getProductList it will call the get on the proxy which will end up loading your children.

With the configuration you have your productList wont load when you fetch all Category rest assured, it will only load when you access the getProductList.

[update] You can follow the url and read the section "How Lazy Loading Works in Hibernate" Hibernate and Lazy loading . That might help you clarify the lazy loading. If you access lazy loaded elements after closing the hibernate session in which it is loaded you will end up with LazyInitializationException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM