Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

failed to lazily initialize a collection of role

Tags:

java

hibernate

Hi I have two classes like this:

public class Indicator implements Serializable {
...

    @OneToMany(mappedBy = "indicator",fetch=FetchType.LAZY)
    private List<IndicatorAlternateLabel>  indicatorAlternateLabels;

    public List<IndicatorAlternateLabel> getIndicatorAlternateLabels() {
        return indicatorAlternateLabels;
    }

        public void setIndicatorAlternateLabels(List<IndicatorAlternateLabel> indicatorAlternateLabels) {
            this.indicatorAlternateLabels = indicatorAlternateLabels;
        }
...
    }

public class IndicatorAlternateLabel implements Serializable {
...
 @ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
    @JoinColumn(name = "IndicatorID")
    @XmlTransient
    private Indicator indicator;
...
}

When I use them like this:

 public MetricTypeDetail getMetricTypeDetail(Integer metricTypeId) {
        Criteria crit = sessionFactory.getCurrentSession().createCriteria(Indicator.class, "sub")
                    .add(Restrictions.eq("number", metricTypeId))
                    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).setCacheable(true);
        crit.setMaxResults(1);
        Indicator indicator=(Indicator) crit.uniqueResult();
        MetricTypeDetail metricTypeDetail=new MetricTypeDetail(indicator);
        List<IndicatorAlternateLabel> indicatorAlternateLabels = null;
        indicatorAlternateLabels=indicator.getIndicatorAlternateLabels();
        metricTypeDetail.setIndicatorAlternateLabels(indicatorAlternateLabels);
        return metricTypeDetail;
    }

This code returns an exception: failed to lazily initialize a collection of role: com.porism.service.domain.Indicator.indicatorAlternateLabels, no session or session was closed

Any idea? I'm very new to Hibernate

like image 526
Lince81 Avatar asked Mar 23 '11 11:03

Lince81


People also ask

How do I fix lazy initialization exception?

The right way to fix a LazyInitializationException is to fetch all required associations within your service layer. The best option for that is to load the entity with all required associations in one query.

Can't initialize proxy no session Hibernate Java?

LazyInitializationException: could not initialize proxy - no Session in Hibernate". Why this error comes, because hibernate needs to go database to initialize the proxy object, and the connection is already closed.

What is Enable_lazy_load_no_trans?

Hibernate has a workaround, an enable_lazy_load_no_trans property. Turning this on means that each fetch of a lazy entity will open a temporary session and run inside a separate transaction.


2 Answers

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.

like image 131
Johan Sjöberg Avatar answered Sep 19 '22 12:09

Johan Sjöberg


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;

}
like image 24
Phaedrus Avatar answered Sep 20 '22 12:09

Phaedrus