Search code examples
javahibernatehibernate-criteria

FetchType.LAZY does not work - Hibernate & Criteria


I have following relation OneToMany:

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "dashboardBox", fetch=FetchType.LAZY)
public List<DashboardCell> getCells() {
    return cells;
}

and in other class ManyToOne:

@ManyToOne(optional = false, fetch=FetchType.LAZY)
@JoinColumn(name="DASHBOARD_BOX_ID")
public DashboardBox getDashboardBox() {
    return dashboardBox;
}

I am trying to query the Boxes without cells (as I have LAZY in cells list). I tried like this:

public List<DashboardBox> findAll(Users user) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(DashboardBox.class)
                .add(Restrictions.eq("userId", user.getId()));
    return criteria.list();
}

Also like this:

public List<DashboardBox> findAll(Users user) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(DashboardBox.class)
                .add(Restrictions.eq("userId", user.getId()))
                .setFetchMode("cells", FetchMode.SELECT);
    return criteria.list();
}

What I want to achieve is to do not have list of cells when i query DashboardBox'es.

Anyone have an idea and can explain my how to achive LAZY loading when using Criteria? I know that if I would use HQL I would have it but I am interested in using Criteria's.

Thanks


Solution

  • I found answer. In my code everything was fine. I did not metnioned that I return this List of DashboardBoxes in spring restful controller with format json. What was happening the list of cells was was not eager fetched but Jackson was forcing hibernate to retrive this list.

    What I needed to add in my WebMvcConfigurerAdapter:

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new Hibernate5Module());
        jacksonConverter.setObjectMapper(mapper);
        converters.add(jacksonConverter);
        super.configureMessageConverters(converters);
    }