Ainda não tem acesso? Estude com a gente! Matricule-se
Ainda não tem acesso? Estude com a gente! Matricule-se

Erro Lazy loading is not implemented.

Caros minha classe LivroDataModel não está executando. Gera o erro de Lazy loading:


public class LivroDataModel extends LazyDataModel<Livro> {

    private static final long serialVersionUID = 1L;

    @Inject
    private LivroDao livroDao;

    @PostConstruct
    void init(){
        super.setRowCount(livroDao.contaTodos());
    }

    @Override
    public List<Livro> load(int first, int pageSize, List<SortMeta> multiSortMeta, Map<String, Object> filters) {
        List<String> colunas = new ArrayList<String>();
        List<String> valores = new ArrayList<String>();

        for (Entry<String, Object> entry : filters.entrySet()) {
            colunas.add(entry.getKey());
            valores.add(entry.getValue().toString());
        } 

        return this.livroDao.listaTodosPaginada(first, pageSize, colunas, valores);
    }    
}

LivroDao

public class LivroDao implements Serializable {

    private static final long serialVersionUID = -6662277994148943606L;

    private DAO<Livro> dao;

    public int contaTodos() {
        return dao.contaTodos();
    }

    public List<Livro> listaTodosPaginada(int firstResult, int maxResults, List<String> colunas, List<String> valores) {
        return dao.listaTodosPaginada(firstResult, maxResults, colunas, valores);
    }

    @Inject
    private EntityManager entityManager;

    @PostConstruct
    public void init() {
        this.dao = new DAO<Livro>(entityManager, Livro.class);
    }

    public void adiciona(Livro t) {
        dao.adiciona(t);
    }

    public void remove(Livro t) {
        dao.remove(t);
    }

    public void atualiza(Livro t) {
        dao.atualiza(t);
    }

    public List<Livro> listaTodos() {
        return dao.listaTodos();
    }

    public Livro buscaPorId(Integer id) {
        return dao.buscaPorId(id);
    }

DAO

public class DAO<T> implements Serializable {

    private final Class<T> classe;
    private EntityManager em;

    public DAO(EntityManager entityManager, Class<T> classe) {
        this.em = entityManager;
        this.classe = classe;
    }

    public void adiciona(T t) {

        // abre transacao
        em.getTransaction().begin();

        // persiste o objeto
        em.persist(t);

        // commita a transacao
        em.getTransaction().commit();
    }

    public void remove(T t) {
        em.getTransaction().begin();

        em.remove(em.merge(t));

        em.getTransaction().commit();
    }

    public void atualiza(T t) {
        em.getTransaction().begin();

        em.merge(t);

        em.getTransaction().commit();
    }

    public List<T> listaTodos() {
        CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
        query.select(query.from(classe));

        List<T> lista = em.createQuery(query).getResultList();

        return lista;
    }

    public T buscaPorId(Integer id) {
        T instancia = em.find(classe, id);
        return instancia;
    }

    public int contaTodos() {
        long result = (Long) em.createQuery("select count(n) from " + classe.getSimpleName() + " n")
                .getSingleResult();

        return (int) result;
    }

    public List<T> listaTodosPaginada(int firstResult, int maxResults) {
        CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
        query.select(query.from(classe));

        List<T> lista = em.createQuery(query).setFirstResult(firstResult)
                .setMaxResults(maxResults).getResultList();

        return lista;
    }

    public List<T> listaTodosPaginada(int firstResult, int maxResults, List<String> colunas, List<String> valores) {
        CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
        Root<T> root = query.from(classe);
        if(valores != null && !valores.isEmpty() && colunas != null && !colunas.isEmpty() && colunas.size() == valores.size()) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            for (int i = 0; i < colunas.size(); i++) {
                predicates.add(em.getCriteriaBuilder().like(root.<String>get(colunas.get(i)), valores.get(i) + "%"));
            }

            query = query.where(predicates.toArray(new Predicate[predicates.size()]));
        }

        List<T> lista = em.createQuery(query).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();

        return lista;
    }
}

Poderiam dar uma ajuda nesse tópico? Não estou conseguindo fazer funcionar com o CDI.

6 respostas

Tem a stack completa do erro?

Hibernate: select autor0_.id as id2_, autor0_.email as email2_, autor0_.nome as nome2_ from Autor autor0_
Hibernate: select count(livro0_.id) as col_0_0_ from Livro livro0_ limit ?
set 18, 2019 9:47:26 AM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
GRAVE: Error Rendering View[/livro.xhtml]
java.lang.UnsupportedOperationException: Lazy loading is not implemented.
    at org.primefaces.model.LazyDataModel.load(LazyDataModel.java:133)
    at br.com.caelum.livraria.modelo.LivroDataModel$Proxy$_$$_WeldClientProxy.load(Unknown Source)
    at org.primefaces.component.datatable.DataTable.loadLazyData(DataTable.java:573)
    at org.primefaces.component.datatable.DataTableRenderer.preRender(DataTableRenderer.java:145)
    at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:93)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

set 18, 2019 9:47:26 AM org.apache.catalina.core.StandardWrapperValve invoke GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/livraria-lazy] threw exception [Lazy loading is not implemented.] with root cause java.lang.UnsupportedOperationException: Lazy loading is not implemented. at org.primefaces.model.LazyDataModel.load(LazyDataModel.java:133) at br.com.caelum.livraria.modelo.LivroDataModel$Proxy$$$WeldClientProxy.load(Unknown Source) at org.primefaces.component.datatable.DataTable.loadLazyData(DataTable.java:573) at org.primefaces.component.datatable.DataTableRenderer.preRender(DataTableRenderer.java:145) at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:93) at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863) at javax.faces.render.Renderer.encodeChildren(Renderer.java:176) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134) at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748)

O seu método "load" na classe "LivroDataModel" está fazendo override?

Sim. Está.

Existem 2 métodos de carregamento no LazyDataModel:

public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
    throw new UnsupportedOperationException("Lazy loading is not implemented.");
}

public List<T> load(int first, int pageSize, List<SortMeta> multiSortMeta, Map<String,String> filters) {
    throw new UnsupportedOperationException("Lazy loading is not implemented.");
}

É aqui que o erro é gerado. Você está usando multisort, tenta sobreescrever o primeiro.