failed to lazily initialize a collection of role

前端 未结 4 813
盖世英雄少女心
盖世英雄少女心 2020-12-12 20:49

Hi I have two classes like this:

public class Indicator implements Serializable {
...

    @OneToMany(mappedBy = \"indicator\",fetch=FetchType.LAZY)
    priv         


        
相关标签:
4条回答
  • 2020-12-12 21:42

    Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.

    You can avoid this problem by

    • accessing the lazy collection within a transaction.
    • Initalizing the collection using Hibernate.initialize(obj);
    • Fetch the collection in another transaction
    • Use Fetch profiles to select lazy/non-lazy fetching runtime
    • Set fetch to non-lazy (which is generally not recommended)

    Further I would recommend looking at the related links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.

    0 讨论(0)
  • 2020-12-12 21:44

    Try swich fetchType from LAZY to EAGER

    ...
    @OneToMany(fetch=FetchType.EAGER)
    private Set<NodeValue> nodeValues;
    ...
    

    But in this case your app will fetch data from DB anyway. If this query very hard - this may impact on performance. More here: https://docs.oracle.com/javaee/6/api/javax/persistence/FetchType.html

    ==> 73

    0 讨论(0)
  • 2020-12-12 21:46

    as suggested here solving the famous LazyInitializationException is one of the following methods:

    (1) Use Hibernate.initialize

    Hibernate.initialize(topics.getComments());

    (2) Use JOIN FETCH

    You can use the JOIN FETCH syntax in your JPQL to explicitly fetch the child collection out. This is somehow like EAGER fetching.

    (3) Use OpenSessionInViewFilter

    LazyInitializationException often occurs in the view layer. If you use Spring framework, you can use OpenSessionInViewFilter. However, I do not suggest you to do so. It may leads to a performance issue if not used correctly.

    0 讨论(0)
  • 2020-12-12 21:50

    It's possible that you're not fetching the Joined Set. Be sure to include the set in your HQL:

    public List<Node> getAll() {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("FROM Node as n LEFT JOIN FETCH n.nodeValues LEFT JOIN FETCH n.nodeStats");
        return  query.list();
    }
    

    Where your class has 2 sets like:

    public class Node implements Serializable {
    
    @OneToMany(fetch=FetchType.LAZY)
    private Set<NodeValue> nodeValues;
    
    @OneToMany(fetch=FetchType.LAZY)
    private Set<NodeStat> nodeStats;
    
    }
    
    0 讨论(0)
提交回复
热议问题