6
respostas

Os dados do livro não são carregados nos campos do formulário

Estou fazendo o CRUD com JSF, mas no exercício para alteração do livro os dados do livro não são carregados nos campos do formulário. Alguém poderia me dar uma ajuda? Meu código:

//LivroBean
public void carregar(Livro livro){
        System.out.println("Carregando o Livro");
        this.livro = livro;    
    }

//livro.xhtml
<h:column>
    <f:facet name="header">Alterar</f:facet>
    <h:commandLink value="alterar" action="#{livroBean.carregar(livro)}" />
</h:column>
6 respostas

O programa dá algum erro ou simplesmente não carrega as informações? Se dá erro pode ser por causa do LazyInitializationException, se não carrega o System.out.println pelo menos é impresso no console?

Você alterou a linha

@ManyToMany(fetch=FetchType.EAGER) private List autores = new ArrayList();

no Livro?

@Marcio Não apresenta exceção. E o println apresenta RENDER_RESPONSE 6. Mas os campos do formulário não são atualizados com os dados quando seleciono alterar.

@Peterson: Sim. Alterei o fetch para EAGER.

Poderia colocar o código do seu bean e do seu xhtml inteiros aqui. Assim fica mais fácil de achar o problema

bean:

package br.com.caelum.livraria.bean;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import br.com.caelum.livraria.dao.DAO;
import br.com.caelum.livraria.modelo.Autor;
import br.com.caelum.livraria.modelo.Livro;
import br.com.caelum.livraria.util.RedirectView;

@ManagedBean
@ViewScoped
public class LivroBean {

    private Livro livro = new Livro();
    private Integer autorId;

    public Livro getLivro() {
        return livro;
    }

    public Integer getAutorId() {
        return autorId;
    }

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

    public List<Autor> getAutores(){
        return new DAO<Autor>(Autor.class).listaTodos();
    }

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

    public void gravarAutor(){
        Autor autor = new DAO<Autor>(Autor.class).buscaPorId(this.autorId);
        this.livro.adicionaAutor(autor);
        System.out.println("livro escrito por: " + autor.getNome());
    }

    public List<Livro> getLivros() {
          return new DAO<Livro>(Livro.class).listaTodos();
    }

    public RedirectView gravar() {
        System.out.println("Gravando livro " + this.livro.getTitulo());

        if (livro.getAutores().isEmpty()) {
            //throw new RuntimeException("Livro deve ter pelo menos um Autor.");
            FacesContext.getCurrentInstance().addMessage("autor", new FacesMessage("Livro deve ter pelo menos 1 autor."));
        }

        if(this.livro.getId() == null){
            new DAO<Livro>(Livro.class).adiciona(this.livro);
        }
        else{
            new DAO<Livro>(Livro.class).atualiza(this.livro);    
        }    

        this.livro = new Livro();

        return new RedirectView("livro");
    }

    public void comecaComDigitoUm(FacesContext fc, UIComponent component, Object value) throws ValidatorException{
        String valor = value.toString();
        if(!valor.startsWith("1")){
            throw new ValidatorException(new FacesMessage("Deveria Começar com 1"));
        }
    }

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

    public void remover(Livro livro){
        System.out.println("Removendo Livro");
        new DAO<Livro>(Livro.class).remove(livro);
    }

    public void carregar(Livro livro){
        System.out.println("Carregando o Livro");
        this.livro = livro;    
    }

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

xhtml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

<h:head />

<ui:composition template="_template.xhtml">
    <ui:define name="titulo">
        Novo Livro
    </ui:define>
    <ui:define name="conteudo">
        <h:form>
            <h:messages id="messages" />
            <fieldset>
                <legend>Dados do Livro</legend>
                <h:panelGrid columns="2">

                    <h:outputLabel value="Titulo:" for="titulo" />
                    <h:inputText id="titulo" value="#{livroBean.livro.titulo}"
                        require="true" requiredMessage="Título Obrigatório"
                        validatorMessage="Título não pode ser superior a 40">
                        <f:validateLength maximum="40" />
                        <f:ajax event="blur" render="messages" />
                    </h:inputText>

                    <h:outputLabel value="ISBN:" for="isbn" />
                    <h:inputText id="isbn" value="#{livroBean.livro.isbn}"
                        validator="#{livroBean.comecaComDigitoUm}">
                        <f:ajax event="keypress" render="messages" />
                    </h:inputText>


                    <h:outputLabel value="Preço:" for="preco" />
                    <h:inputText id="preco" value="#{livroBean.livro.preco}"
                        required="true"
                        validatorMessage="Valor deve ser entre R$1,00 e R$1000,00">
                        <f:validateDoubleRange minimum="1.00" maximum="1000.00" />
                    </h:inputText>

                    <h:outputLabel value="Data de Lançamento:" for="dataLancamento" />
                    <h:inputText id="dataLancamento"
                        value="#{livroBean.livro.dataLancamento.time}">
                        <f:convertDateTime pattern="dd/MM/yyyy HH:mm" />
                    </h:inputText>
                </h:panelGrid>
            </fieldset>

            <fieldset>
                <legend>Dados do Autor</legend>
                <h:outputLabel value="Selecione Autor" for="autor" />
                <h:selectOneMenu value="#{livroBean.autorId}" id="autor">
                    <f:selectItems value="#{livroBean.autores}" var="autor"
                        itemLabel="#{autor.nome}" itemValue="#{autor.id}" />
                </h:selectOneMenu>
                <h:commandButton value="Gravar Autor"
                    action="#{livroBean.gravarAutor}">
                    <f:ajax execute="autor" render="tabelaDeAutores" />
                </h:commandButton>

                <h:commandLink value="Cadastrar Novo Autor"
                    action="#{livroBean.formAutor}" immediate="true" />
                <br />

                <h:dataTable value="#{livroBean.autoresDoLivro}" var="autor"
                    id="tabelaDeAutores">
                    <h:column>
                        <h:outputText value="#{autor.nome}" />
                    </h:column>
                    <h:column>
                        <h:commandLink value="X"
                            action="#{livroBean.removerAutorDoLivro(autor)}" />
                    </h:column>

                </h:dataTable>
            </fieldset>


            <h:commandButton value="Gravar" action="#{livroBean.gravar}">
                <f:ajax execute="@form" render="@form tabelaLivros" />
            </h:commandButton>

            <h:dataTable value="#{livroBean.livros}" var="livro"
                id="tabelaLivros">
                <h:column>
                    <f:facet name="header">Título</f:facet>
                    <h:outputText value="#{livro.titulo}" />
                </h:column>

                <h:column>
                    <f:facet name="header">ISBN</f:facet>
                    <h:outputText value="#{livro.isbn}" />
                </h:column>

                <h:column>
                    <f:facet name="header">Preço</f:facet>
                    <h:outputText value="#{livro.preco}" />
                </h:column>

                <h:column>
                    <f:facet name="header">Data</f:facet>
                    <h:outputText value="#{livro.dataLancamento.time}">
                        <f:convertDateTime pattern="dd/MM/yyyy HH:mm" />
                    </h:outputText>
                </h:column>

                <h:column>
                    <f:facet name="header">Remover</f:facet>
                    <h:commandLink value="remover" action="#{livroBean.remover(livro)}" immediate="true" />
                </h:column>
                <h:column>
                    <f:facet name="header">Alterar</f:facet>
                    <h:commandLink value="alterar"
                        action="#{livroBean.carregar(livro)}" />
                </h:column>

            </h:dataTable>
        </h:form>
    </ui:define>
    <ui:define name="texto">
          Cadastro de Livros
    </ui:define>
</ui:composition>

</html>

Olá,

Já tentou:

<h:commandLink value="alterar"
                        action="#{livroBean.carregar(livro)}">
    <f:ajax execute="@this" render="@form" immediate="true" />
</h:commandLink>

Atenciosamente.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software