Selectonemenu (Primefaces) field not saved in the seat

Asked

Viewed 148 times

1

I’ve come to ask for your help again because I need to finish my CBT. I have a dialog which has several fields, one of them is a <p:selectOneMenu>. When I fill in all fields and go save, all fields are saved except the field <p:selectOneMenu>. And no error appears in stacktrace. I’ve debugged, researched about Converter and a thousand other things....

UPDATING

Observing Hibernate’s appointments, I realized that he does the insert in all fields except auxiliary class monografia_linhapesquisa,because I have a relationship Manytomany amid Monografia and LinhaPesquisa Below the console output:

Hibernate: Insert into monograph (aluno_id, data_inicio, professor_id, title) values (?, ?, ?, ?)

I have the following mapping between Monografia and LinhaPesquisa. In class LinhaPesquisa I made no relationship

@ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinTable(name="monografia_linhapesquisa", joinColumns=
    {@JoinColumn(name="monografia_id")}, inverseJoinColumns=
    {@JoinColumn(name="linha_pesquisa_id")})
    private List<LinhaPesquisa> listaLinhaPesquisas;

Man <p:selectOneMenu>

        <p:outputLabel value="Linha de Pesquisa: " for="linhaPesquisa" />
            <p:selectOneMenu id="linhaPesquisa" converter="#{gestaoMonografiasBean.linhaPesquisaConverter}"
                value="#{gestaoMonografiasBean.monografia.linhaPesquisa}" required="true" >
                <f:selectItem itemLabel="Selecione..." />
                <f:selectItems value="#{gestaoMonografiasBean.selecionarLinhaPesquisa}"
                    var="linhaPesquisa" itemLabel="#{linhaPesquisa.titulo}"
                    itemValue="#{linhaPesquisa}" />
            </p:selectOneMenu>

My method selecionarLinhaPesquisa that stays in my bean, which I use to access the Linha de Pesquisa, after searching I pass the list to the Converter

public List<LinhaPesquisa> getSelecionarLinhaPesquisa() {
        List<LinhaPesquisa> listaLinhaPesquisas = linhaPesquisas.todas();

        linhaPesquisaConverter = new LinhaPesquisaConverter(listaLinhaPesquisas);

        return listaLinhaPesquisas;
    }

My method of searching the bank

public List<LinhaPesquisa> todas() {
        return manager.createQuery("from LinhaPesquisa", LinhaPesquisa.class).getResultList();
   }

And finally my Converter, which I think is working normal, because I debugged and saw that arrives in the getAsObject method id concerning Linha de Pesquisa selected, but not saved on the seat.

package com.daniel.monografia.controller.converter;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import com.daniel.monografia.model.LinhaPesquisa;

public class LinhaPesquisaConverter implements Converter {

    private List<LinhaPesquisa> listaLinhaPesquisas;



    public LinhaPesquisaConverter(List<LinhaPesquisa> listaLinhaPesquisas) {
        this.listaLinhaPesquisas = listaLinhaPesquisas;
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        System.out.println("Objeto linha pesquisa: " + value);
        if (value == null || value.isEmpty()) {
            throw new ConverterException("Erro de Conversão: value null ou vazio");

        }

         Long id = Long.valueOf(value);

         for(LinhaPesquisa linhaPesquisa: listaLinhaPesquisas){
         if(id.equals(linhaPesquisa.getId())){ 
             return linhaPesquisa; 
            } 
         }

         return null;

    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        System.out.println("Strinh linha de pesquisa: "+value);

        if(value == null){
            return "";
        }

        try{
            if(value instanceof LinhaPesquisa && value != null){

                return String.valueOf(((LinhaPesquisa) value).getId());
            }else{

            }
        }catch(NumberFormatException e){
            throw new ConverterException(new FacesMessage(String.format("Selecione uma Linha de Pesquisa", value)), e);
        }
        return null;

    }

}

My method of searching the list of Linhas de Pesquisa of my bean, that caught the objects to persist in the object monografia

public List<LinhaPesquisa> getSelecionarLinhaPesquisa() {
        List<LinhaPesquisa> listaLinhaPesquisas = linhaPesquisas.todas();

        linhaPesquisaConverter = new LinhaPesquisaConverter(listaLinhaPesquisas);

        return listaLinhaPesquisas;
    }

The method todas() in the repository linhasPesquisas

public List<LinhaPesquisa> todas() {
        return manager.createQuery("from LinhaPesquisa", LinhaPesquisa.class).getResultList();
   }

The bean GestaoMonografiasBean complete

package com.daniel.monografia.controller;

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

import javax.annotation.PostConstruct;
import javax.faces.convert.Converter;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.context.RequestContext;

import com.daniel.monografia.controller.converter.AlunoConverter;
import com.daniel.monografia.controller.converter.LinhaPesquisaConverter;
import com.daniel.monografia.controller.converter.ProfessorConverter;
import com.daniel.monografia.model.Aluno;
import com.daniel.monografia.model.LinhaPesquisa;
import com.daniel.monografia.model.Monografia;
import com.daniel.monografia.model.Pessoa;
import com.daniel.monografia.model.Professor;
import com.daniel.monografia.repository.Alunos;
import com.daniel.monografia.repository.LinhaPesquisas;
import com.daniel.monografia.repository.Monografias;
import com.daniel.monografia.repository.Professores;
import com.daniel.monografia.service.CadastroMonografiaService;
import com.daniel.monografia.util.FacesMessages;

@Named
@ViewScoped
public class GestaoMonografiasBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private Monografias monografias;

    @Inject
    private FacesMessages messages;

    @Inject
    private Professores professores;

    @Inject
    private Alunos alunos;

    @Inject
    private LinhaPesquisas linhaPesquisas;

    @Inject
    private CadastroMonografiaService cadastroMonografiaService;

    private List<Monografia> listaMonografias;

    private List<LinhaPesquisa> listaLinhaPesquisas;

    private String termoPesquisa;

    private Converter professorConverter;

    private Converter alunoConverter;

    private Converter linhaPesquisaConverter;

    private Monografia monografia;

    private Aluno aluno;

    private Professor professor;



    @PostConstruct
    private void iniciar() {
        monografia = new Monografia();

        aluno = new Aluno();
        this.aluno.setPessoa(new Pessoa());

        professor = new Professor();
        this.professor.setPessoa(new Pessoa());

        listaLinhaPesquisas = linhaPesquisas.todas();


    }

    public void prepararNovaMonografia() {

    }

    public void prepararEdicao() {
        professorConverter = new ProfessorConverter(Arrays.asList(monografia.getProfessor()));
        alunoConverter = new AlunoConverter(Arrays.asList(monografia.getAluno()));
    }

    public void salvar() {
        System.out.println("*********************Objeto: ***********************" + monografia);
        try {
            cadastroMonografiaService.salvar(monografia);

            atualizarRegistros();

            messages.info("Monografia salva com sucesso!");

            RequestContext.getCurrentInstance().update(Arrays.asList("frm:monografiasDataTable", "frm:messages"));

        } catch (Exception erro) {
            erro.printStackTrace();
        }
    }

    public void excluir() {
        cadastroMonografiaService.excluir(monografia);

        monografia = null;

        atualizarRegistros();

        messages.info("Monografia excluída com sucesso!");
    }

    public void pesquisar() {
        listaMonografias = monografias.pesquisar(termoPesquisa);

        if (listaMonografias.isEmpty()) {
            messages.info("Sua consulta não retornou registros.");
        }
    }

    public void todasMonografias() {
        listaMonografias = monografias.todas();
    }

    public List<Professor> completarProfessor(String termo) {
        List<Professor> listaProfessores = professores.pesquisar(termo);

        professorConverter = new ProfessorConverter(listaProfessores);

        return listaProfessores;
    }

    public List<Aluno> completarAluno(String termo) {
        List<Aluno> listaAlunos = alunos.pesquisar(termo);

        alunoConverter = new AlunoConverter(listaAlunos);

        return listaAlunos;
    }

    public List<LinhaPesquisa> getSelecionarLinhaPesquisa() {
        List<LinhaPesquisa> listaLinhaPesquisas = linhaPesquisas.todas();

        linhaPesquisaConverter = new LinhaPesquisaConverter(listaLinhaPesquisas);

        return listaLinhaPesquisas;
    }

    private void atualizarRegistros() {
        if (jaHouvePesquisa()) {
            pesquisar();
        } else {
            todasMonografias();
        }
    }

    private boolean jaHouvePesquisa() {
        return termoPesquisa != null && !"".equals(termoPesquisa);
    }

    public List<Monografia> getListaMonografias() {
        return listaMonografias;
    }

    public List<LinhaPesquisa> getListaLinhaPesquisas() {
        return listaLinhaPesquisas;
    }

    public void setListaLinhaPesquisas(List<LinhaPesquisa> listaLinhaPesquisas) {
        this.listaLinhaPesquisas = listaLinhaPesquisas;
    }

    public String getTermoPesquisa() {
        return termoPesquisa;
    }

    public void setTermoPesquisa(String termoPesquisa) {
        this.termoPesquisa = termoPesquisa;
    }

    public Converter getProfessorConverter() {
        return professorConverter;
    }

    public void setProfessorConverter(Converter professorConverter) {
        this.professorConverter = professorConverter;
    }

    public Converter getAlunoConverter() {
        return alunoConverter;
    }

    public void setAlunoConverter(Converter alunoConverter) {
        this.alunoConverter = alunoConverter;
    }

    public Converter getLinhaPesquisaConverter() {
        return linhaPesquisaConverter;
    }

    public void setLinhaPesquisaConverter(Converter linhaPesquisaConverter) {
        this.linhaPesquisaConverter = linhaPesquisaConverter;
    }

    public Monografia getMonografia() {
        return monografia;
    }

    public void setMonografia(Monografia monografia) {
        this.monografia = monografia;
    }

    public Aluno getAluno() {
        return aluno;
    }

    public void setAluno(Aluno aluno) {
        this.aluno = aluno;
    }

    public boolean isMonografiaSeleciona() {
        return monografia != null && monografia.getId() != null;
    }
}

The class Monografia that makes the relationship ManytoMany with class LinhaPesquisa

package com.daniel.monografia.model;

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

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name="monografia")
public class Monografia implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotEmpty
    @Column(nullable = false, length = 120)
    private String titulo;

    @NotNull
    @Past
    @Temporal(TemporalType.DATE)
    @Column(name = "data_inicio")
    private Date dataInicio;


    @NotNull
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "aluno_id")
    private Aluno aluno;

    @NotNull
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "professor_id")
    private Professor professor;

    @ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinTable(name="monografia_linhapesquisa", joinColumns=
    {@JoinColumn(name="monografia_id")}, inverseJoinColumns=
    {@JoinColumn(name="linha_pesquisa_id")})
    private List<LinhaPesquisa> listaLinhaPesquisas; 

    @Transient
    private LinhaPesquisa linhaPesquisa;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }


    public Date getDataInicio() {
        return dataInicio;
    }

    public void setDataInicio(Date dataInicio) {
        this.dataInicio = dataInicio;
    }

    public List<LinhaPesquisa> getLinhaPesquisas() {
        return listaLinhaPesquisas;
    }

    public void setLinhaPesquisas(List<LinhaPesquisa> linhaPesquisas) {
        this.listaLinhaPesquisas = linhaPesquisas;
    }

    public Aluno getAluno() {
        return aluno;
    }

    public void setAluno(Aluno aluno) {
        this.aluno = aluno;
    }

    public Professor getProfessor() {
        return professor;
    }

    public void setProfessor(Professor professor) {
        this.professor = professor;
    }

    public LinhaPesquisa getLinhaPesquisa() {
        return linhaPesquisa;
    }

    public void setLinhaPesquisa(LinhaPesquisa linhaPesquisa) {
        this.linhaPesquisa = linhaPesquisa;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Monografia other = (Monografia) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Monografia [id=" + id + "]";
    }
}
  • Someone could give a boost?

  • 1

    What object are you trying to persist with? Where is its implementation? It seems to me that you are not setting the value of the persisted object according to what is being selected from selectOneMenu.

  • Thanks @Karanalvespereira I will update the post, thanks in advance for the help

  • 1

    In the debug you observed if at the time of saving the monograph object, the monograph.line ?

  • Yes is filled in. With id and title

  • @Douglas Thanks for the help. I’ll put the class Monografia that has the mapemaneto Manytomany with the class LinhaPesquisa, I am suspecting that the relationship is not correct. In case I am working with an auxiliary class monografia_linhapesquisa and eacho that she is not receiving the ``monografia_ideline_search_id`

  • I don’t know if that’s it, but I think JPA/Hibernate is not persisting to the auxiliary table monografia_linhapesquisa containing the key monografia_id and linha_pesqusia_id&#I’m sorry, but it must be a basic problem and I don’t see it because I’m new in this world

  • @Karanalvespereira I updated the post. I realized that Hibernate doesn’t do the Index or update in the table monografia_linhapesquisa

  • 1

    Why the mapping is as @Manytomany, if you are using the selectOneMenu component that allows you to select only one record?

  • @Karanalvespereira Thank you so much man! I used the component <p:selectCheckboxMenu> and showed the attribute in datatable, now has another problem, it only shows one attribute, I want it to show everyone who was selected. And sorry to bother you with this silly beginner mistake, you helped me with my TCC, thanks!

Show 5 more comments

1 answer

1


1 - You are using @Manytomany mapping for a component that allows you to select only 1 record.

Solution: Switch component to selectCheckboxnu

2 - In the datatable it only shows an attribute, I want it to show all who were selected

Solution 1: As this field is a List, I suggest creating a new field in your entity that presents the information of the list concatenated and separated by comma. In the get of this field, you can do a go on top of the List to return this information. Then in the datatable, just inform this field that you created.

Solution 2: You can override the Tostring() method from your list and return it any way you want by calling the list itself in the datatable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.