1
resposta

Problema ao carregar o Autor do Livro

Olá Nico. Após colocar o projeto livraria-wildfly para rodar pude notar que não está carregando os autores ao tentar alterar um livro.

22:42:31,506 INFO  [stdout] (default task-14) FASE: RESTORE_VIEW 1

22:42:31,554 INFO  [stdout] (default task-14) /livro.xhtml

22:42:31,555 INFO  [stdout] (default task-14) FASE: APPLY_REQUEST_VALUES 2

22:42:31,559 INFO  [stdout] (default task-14) FASE: PROCESS_VALIDATIONS 3

22:42:31,568 INFO  [stdout] (default task-14) FASE: UPDATE_MODEL_VALUES 4

22:42:31,577 INFO  [stdout] (default task-14) FASE: INVOKE_APPLICATION 5

22:42:31,579 INFO  [stdout] (default task-14) Carregando livro

22:42:31,584 INFO  [stdout] (default task-14) Hibernate: select livro0_.id as id1_1_0_, livro0_.dataLancamento as dataLanc2_1_0_, livro0_.isbn as isbn3_1_0_, livro0_.preco as preco4_1_0_, livro0_.titulo as titulo5_1_0_ from Livro livro0_ where livro0_.id=?

22:42:31,593 INFO  [stdout] (default task-14) FASE: RENDER_RESPONSE 6

22:42:31,648 INFO  [stdout] (default task-14) Hibernate: select autor0_.id as id1_0_, autor0_.email as email2_0_, autor0_.nome as nome3_0_ from Autor autor0_

22:42:31,672 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (default task-14) Error Rendering View[/livro.xhtml]: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: br.com.caelum.livraria.modelo.Livro.autores, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:567)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:205)
    at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:146)
    at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:261)
    at javax.faces.model.ListDataModel.isRowAvailable(ListDataModel.java:109)
    at javax.faces.model.ListDataModel.setRowIndex(ListDataModel.java:184)
    at javax.faces.model.ListDataModel.setWrappedData(ListDataModel.java:219)
    at javax.faces.model.ListDataModel.<init>(ListDataModel.java:78)
    at org.primefaces.component.api.UIData.getDataModel(UIData.java:767)
    at javax.faces.component.UIData.getRowCount(UIData.java:356)
    at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:806)
    at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:788)
    at org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:281)
    at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:243)
    at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:85)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:89)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:72)
    at org.primefaces.component.fieldset.FieldsetRenderer.encodeContent(FieldsetRenderer.java:94)
    at org.primefaces.component.fieldset.FieldsetRenderer.encodeMarkup(FieldsetRenderer.java:76)
    at org.primefaces.component.fieldset.FieldsetRenderer.encodeEnd(FieldsetRenderer.java:47)
    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 com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:582)
    at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
    at javax.faces.component.UIForm.visitTree(UIForm.java:381)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
    at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:403)
    at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:322)
    at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:60)
    at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:1004)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:432)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    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 io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

22:42:31,675 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (default task-14) org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: br.com.caelum.livraria.modelo.Livro.autores, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:567)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:205)
    at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:146)
    at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:261)
    at javax.faces.model.ListDataModel.isRowAvailable(ListDataModel.java:109)
    at javax.faces.model.ListDataModel.setRowIndex(ListDataModel.java:184)
    at javax.faces.model.ListDataModel.setWrappedData(ListDataModel.java:219)
    at javax.faces.model.ListDataModel.<init>(ListDataModel.java:78)
    at org.primefaces.component.api.UIData.getDataModel(UIData.java:767)
    at javax.faces.component.UIData.getRowCount(UIData.java:356)
    at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:806)
    at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:788)
    at org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:281)
    at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:243)
    at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:85)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:89)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:72)
    at org.primefaces.component.fieldset.FieldsetRenderer.encodeContent(FieldsetRenderer.java:94)
    at org.primefaces.component.fieldset.FieldsetRenderer.encodeMarkup(FieldsetRenderer.java:76)
    at org.primefaces.component.fieldset.FieldsetRenderer.encodeEnd(FieldsetRenderer.java:47)
    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 com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:582)
    at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
    at javax.faces.component.UIForm.visitTree(UIForm.java:381)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
    at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:403)
    at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:322)
    at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:60)
    at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:1004)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:432)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    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 io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
1 resposta

Boa noite Thiago, Estive fazendo o curso e tive o mesmo problema. Depois de dias, resolvi alterando a classe Livro, não sei se é a melhor forma, mas funcionou. Segue:

package br.com.caelum.livraria.bean;

import java.io.Serializable;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;

import br.com.caelum.livraria.dao.AutorDao;
import br.com.caelum.livraria.dao.LivroDao;
import br.com.caelum.livraria.modelo.Autor;
import br.com.caelum.livraria.modelo.Livro;

@Named
@ViewScoped
public class LivroBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private Livro livro = new Livro();

    private Integer autorId;

    private List<Livro> livros;

    @Inject
    LivroDao livroDao;

    @Inject
    AutorDao autorDao;

    @Inject
    FacesContext context;

    public void setAutorId(Integer autorId) {
        this.autorId = autorId;
    }

    public Integer getAutorId() {
        return autorId;
    }

    public Livro getLivro() {
        return livro;
    }

    public List<Livro> getLivros() {
        if (this.livros == null) {
            this.livros = livroDao.listaTodos();
        }
        return livros;
    }

    public List<Autor> getAutores() {
        return autorDao.listaTodos();
    }

    public List<Autor> getAutoresDoLivro() {
        return this.livro.getAutores();
    }

    public void carregarLivroPelaId() {
        this.livro = livroDao.buscaPorId(this.livro.getId());
    }

    public void gravarAutor() {
        Autor autor = autorDao.buscaPorId(this.autorId);
        this.livro.adicionaAutor(autor);
        System.out.println("Escrito por: " + autor.getNome());
    }

    // begin
    @Transactional
    public void gravar() {
        System.out.println("Gravando livro " + this.livro.getTitulo());

        if (livro.getAutores().isEmpty()) {
            context.addMessage("autor", new FacesMessage(
                    "Livro deve ter pelo menos um Autor."));
            return;
        }

        if (this.livro.getId() == null) {
            livroDao.adiciona(this.livro);
            this.livros = livroDao.listaTodos();
        } else {
            livroDao.atualiza(this.livro);
            this.livros = livroDao.listaTodos();
        }

        this.livro = new Livro();
    }

    // commit

    @Transactional
    public void remover(Livro livro) {
        System.out.println("Removendo livro");
        livroDao.remove(livro);
        this.livros = livroDao.listaTodos();
    }

    public void removerAutorDoLivro(Autor autor) {
        this.livro.removeAutor(autor);
    }

    @Transactional
    public void carregar(Livro livro) {
        System.out.println("Carregando livro");
        this.livro = this.livroDao.buscaPorId(livro.getId());
    }

    public String formAutor() {
        System.out.println("Chamanda do formulário do Autor.");
        return "autor?faces-redirect=true";
    }

    public void comecaComDigitoUm(FacesContext fc, UIComponent component,
            Object value) throws ValidatorException {

        String valor = value.toString();
        if (!valor.startsWith("1")) {
            throw new ValidatorException(new FacesMessage(
                    "ISBN deveria começar com 1"));
        }

    }
}