Value is not being written to the bank

Asked

Viewed 109 times

0

I have the following entities:

package br.com.pokemax.modelo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;

import lombok.Getter;
import lombok.Setter;

@Entity
@Table(name = "habilidade", uniqueConstraints = @UniqueConstraint(columnNames = { "nome" }))
public class Habilidade {

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

    @Getter
    @Setter
    @NotBlank(message = "Nome não pode estar em branco.")
    @Pattern(regexp = "[A-z]*", message = "Atenção, digite somente letras")
    @Size(max = 20, message = "Máximo de 20 caracteres permitidos.")
    @Column(length = 20, nullable = false)
    private String nome;

    @Getter
    @Setter
    @NotBlank
    @Size(max = 150, message = "Máximo de 150 caracteres permitidos.")
    @Column(length = 150, nullable = false)
    private String descricao;

    @Getter
    @Setter
    @NotBlank
    @Size(max = 150, message = "Máximo de 150 caracteres permitidos.")
    @Column(name = "texto_in_game", length = 150, nullable = false)
    private String textoInGame;

    @Getter
    @Setter
    @Column(length = 150, name = "efeito_secundario", nullable = true)
    private String efeitoSecundario;

    @Getter
    @Setter
    @ManyToOne
    private Geracao geracao;

    public Habilidade() {

    }

}

package br.com.pokemax.modelo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;

import lombok.Getter;
import lombok.Setter;

@Entity
@Table(name = "geracao")
public class Geracao {

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

    @Getter
    @Setter
    @NotBlank(message = "Nome não pode estar em branco.")
    @Pattern(regexp = "[A-z]*", message = "Atenção, digite somente letras")
    @Size(max = 20, message = "Máximo de 20 caracteres permitidos.")
    @Column(length = 20, nullable = false)
    private String nome;

    @Getter
    @Setter
    @Min(1)
    @Max(7)
    private Integer numero;

    @Getter
    @Setter
    @Column(name = "total_pokemons", nullable = false)
    private Integer totalPokemons;

    public Geracao() {

    }

}

The following Controller:

package br.com.pokemax.controle;

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

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;

import br.com.pokemax.modelo.Geracao;
import br.com.pokemax.modelo.Habilidade;
import br.com.pokemax.negocio.GeracaoDAO;
import br.com.pokemax.negocio.HabilidadeDAO;
import br.com.pokemax.util.MensagensUtil;
import br.com.pokemax.util.ValidadorUtil;
import lombok.Getter;
import lombok.Setter;

@ViewScoped
@ManagedBean(name = "habilidademb")
public class ControleHabilidade implements Serializable {

    private static final long serialVersionUID = 1L;

    @Getter
    @Setter
    private Habilidade habilidade;

    @Inject
    private HabilidadeDAO dao;

    @Getter
    @Setter
    private Boolean efeitoSecundario;

    @Getter
    @Setter
    private List<Habilidade> lista;

    @Inject
    GeracaoDAO gDao;

    @Getter
    @Setter
    private Geracao geracao;

    @Getter
    @Setter
    private List<Geracao> geracoes;

    @PostConstruct
    public void inicio() {

    }

    public void novo() {
        habilidade = new Habilidade();
    }

    public void gravar() {
        try {
            if (habilidade.getId() == null) {
                dao.insert(habilidade);
                MensagensUtil.msg("Info", "cadastro.sucesso", new Object[] { MensagensUtil.get("habilidade") });
                habilidade = new Habilidade();
            } else {
                dao.update(habilidade);
                MensagensUtil.msg("Info", "alterado.sucesso", new Object[] { MensagensUtil.get("habilidade") });
            }

        } catch (Exception e) {
            e.getMessage();
            return;
        }

    }

    public void pesquisar() {
        try {
            lista = dao.findAll();
            for (Habilidade habilidade : lista) {
                habilidade.setDescricao(ValidadorUtil.checkTipoPokemon(habilidade.getDescricao()));
                habilidade.setTextoInGame(ValidadorUtil.checkTipoPokemon(habilidade.getTextoInGame()));
                habilidade.setDescricao(ValidadorUtil.checkAtributoPokemon(habilidade.getDescricao()));
            }

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

    public void excluir(Habilidade h) {
        try {
            dao.delete(h);
            MensagensUtil.msg("Info", "removido.sucesso", new Object[] { MensagensUtil.get("habilidade") });
            pesquisar();
        } catch (Exception e) {
            e.getMessage();
        }
    }

    public void editar(Long id) {
        try {
            setHabilidade(dao.find(id));
        } catch (Exception e) {
            e.getMessage();
        }

    }

    public void cancelar() {
        habilidade = null;

    }

    public List<Geracao> listarGeracoes() throws Exception {

        this.geracoes = gDao.findAll();
        return this.geracoes;
    }

}

I’m implementing an autocomplete that’s like this:

<p:autoComplete id="geracao" value="#{habilidademb.geracao}" completeMethod="#{habilidademb.listarGeracoes()}"
                        dropdown="true" var="bean" itemLabel="#{bean.nome}" itemValue="#{bean}" converter="geracaoConverter"/>

And my Converter:

package br.com.pokemax.modelo.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.pokemax.modelo.Geracao;
import br.com.pokemax.negocio.GeracaoDAO;

@FacesConverter(value = "geracaoConverter", forClass = Geracao.class)
public class GeracaoConverter implements Converter {

    GeracaoDAO dao = new GeracaoDAO();

    @Override
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) {
        try {
            Geracao d = dao.find(Long.parseLong(value));
            return d;
        } catch (Exception e) {
            e.getMessage();
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext arg0, UIComponent arg1, Object object) {
        if (object != null) {
            return String.valueOf(((Geracao) object).getId());
        } else {
            return null;
        }
    }

}

When I click on the autocomplete, it shows the Generations, but when I select and record, it does not save the geracao_id in the bank. Debugging I realized that the generating object is going null, someone knows how I can solve ?

I’m in the wrong:

18:27:50,276 ERROR [stderr] (default task-6) java.lang.Nullpointerexception 18:27:50,277 ERROR [stderr] (default task-6) at br.com.pokemax.modelo.converter.GeracaoConverter.getAsObject(Geracaoconverter.java:28) 18:27:50,277 ERROR [stderr] (default task-6) at org.primefaces.Component.autocomplete.Autocompleterenderer.getConvertedValue(Autocompleterenderer.java:670) 18:27:50,278 ERROR [stderr] (default task-6) at javax.faces.Component.UIInput.getConvertedValue(Uiinput.java:1045) 18:27:50,278 ERROR [stderr] (default task-6) at javax.faces.Component.UIInput.validate(Uiinput.java:975) 18:27:50,278 ERROR [stderr] (default task-6) at javax.faces.Component.UIInput.executeValidate(Uiinput.java:1248) 18:27:50,278 ERROR [stderr] (default task-6) at javax.faces.Component.UIInput.processValidators(Uiinput.java:712) 18:27:50,278 ERROR [stderr] (default task-6) at javax.faces.Component.UIComponentBase.processValidators(Uicomponentbase.java:1261) 18:27:50,278 ERROR [stderr] (default task-6) at javax.faces.Component.UIComponentBase.processValidators(Uicomponentbase.java:1261) 18:27:50,279 ERROR [stderr] (default task-6) at org.primefaces.Component.panel.Panel.processValidators(Panel.java:299) 18:27:50,279 ERROR [stderr] (default task-6) at javax.faces.Component.UIForm.processValidators(Uiform.java:253) 18:27:50,279 ERROR [stderr] (default task-6) at javax.faces.Component.UIComponentBase.processValidators(Uicomponentbase.java:1261) 18:27:50,279 ERROR [stderr] (default task-6) at javax.faces.Component.UIComponentBase.processValidators(Uicomponentbase.java:1261) 18:27:50,279 ERROR [stderr] (default task-6) at javax.faces.Component.UIViewRoot.processValidators(Uiviewroot.java:1195) 18:27:50,280 ERROR [stderr] (default task-6) at com.sun.faces.lifecycle.Processvalidationsphase.execute(Processvalidationsphase.java:76) 18:27:50,280 ERROR [stderr] (default task-6) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) 18:27:50,281 ERROR [stderr] (default task-6) at com.sun.faces.lifecycle.Lifecycleimpl.execute(Lifecycleimpl.java:198) 18:27:50,282 ERROR [stderr] (default task-6) at javax.faces.webapp.FacesServlet.service(Facesservlet.java:658) 18:27:50,282 ERROR [stderr] (default task-6) at io.undertow.Servlet.handlers.Servlethandler.handleRequest(Servlethandler.java:85))

3 answers

2

I will also leave an implementation of a very good generic converter. We use a similar one in the company. The advantage is that it is not necessary to search in a BD, the object is saved in the component itself.

public class SimpleEntityConverter implements Converter {  

public Object getAsObject(FacesContext ctx, UIComponent component, String value) {  
    if (value != null) {  
        return this.getAttributesFrom(component).get(value);  
    }  
    return null;  
}  

public String getAsString(FacesContext ctx, UIComponent component, Object value) {  

    if (value != null  
            && !"".equals(value)) {  

        BaseEntity entity = (BaseEntity) value;  

        // adiciona item como atributo do componente  
        this.addAttribute(component, entity);  

        Long codigo = entity.getId();  
        if (codigo != null) {  
            return String.valueOf(codigo);  
        }  
    }  

    return (String) value;  
}  

protected void addAttribute(UIComponent component, BaseEntity o) {  
    String key = o.getId().toString(); // codigo da empresa como chave neste caso  
    this.getAttributesFrom(component).put(key, o);  
}  

protected Map<String, Object> getAttributesFrom(UIComponent component) {  
    return component.getAttributes();  
}  

}  

Source: http://www.rponte.com.br/2008/07/26/entity-converters-pra-da-e-vender/

0

-1

Did not miss the @Inject of GeracaoDAO in Convert? Try debugging the convert to see if the returns are correct.

  • I was working at lunchtime, can you believe that after I got back to work I kept thinking about it ? I mean, I was convinced, at home I’ll test and tell you, thank you.

  • Very strange, the dao is still null. :(

  • He’s not crossing this line: Geracao d = dao.find(Long.parseLong(value));

  • Wouldn’t you like to try a generic converter? It has a very good converter for most cases (Simpleentityconverter) http://www.rponte.com.br/2008/07/26/entity-converters-pra-da-e-vender/

  • I edited the question with my mistake

  • Now passed in the convert, but the generating attribute is going as null.

  • You said dao is null or his result?

  • It is null when I arrive at the getAsObject method.

  • Maybe it can’t be injected into the convert. I’m not sure. I advise to do a test with this Simpleentityconverter, it writes the data in the component itself. In the case of your class, I think it works fine because she has the getId().

  • Got it, I’ll post the answer.

  • Very good, thanks for the return.

Show 6 more comments

Browser other questions tagged

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