zdratoz
zdratoz

Reputation: 11

failed to lazily initialize a collection and vaadin

Hello I have a problem with vaadin and lazy load of my entity my entity contains a rellationship one-to-many and many-to-one with this way

@Entity 
@Table(name = "Categories")
public class Category extends AbstractEntity {
private static final long serialVersionUID = 1L;

private String name;
@ManyToOne
@JoinColumn(name = "parent")
private Category parent; 
@Column
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
private List<Category> children = new ArrayList<>(); 

public Category() { } 

so i have this controller

  @Transactional 
  public class CategoryService{

  @PersistenceContext
  private EntityManager em;


public void save(Category category) {
     ..
}


public Collection<Category> all() {
    return em
            .createQuery("select category  from Category category",Category.class)
            .getResultList();

}

when i try to load and print for each entity her children it was successfull but it was on setup.When i use my form in vaadin and i call service.all() and try to do the same thing i have the

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: models.Category.children, could not initialize proxy - no Session

Service:

@Inject 
public CategoriesView(CategoryService service) { 
    this.service = service; 
    list= (List<Category>) service.all(); 
} 

@Override 
protected Component initContent() { 
    HorizontalLayout layout = new HorizontalLayout(); 
    for (Category cate : list) { 
        System.out.println(cate.getChildren()); 
    }
}

What can i do to have wanted result?

Upvotes: 0

Views: 830

Answers (1)

zdratoz
zdratoz

Reputation: 11

i solved my problem by this way i initialized my data-providers in my enter method and i did this

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
    parents = DataProvider.ofCollection(service.all());
    parentGrid.setDataProvider(parents);

}

edit also i put my selectionListener into the enter method

Upvotes: 1

Related Questions