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))
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.
– Roknauta
Very strange, the dao is still null. :(
– Roknauta
He’s not crossing this line:
Geracao d = dao.find(Long.parseLong(value));
– Roknauta
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/
– Marcus Martins
I edited the question with my mistake
– Roknauta
Now passed in the convert, but the generating attribute is going as null.
– Roknauta
You said dao is null or his result?
– Marcus Martins
It is null when I arrive at the getAsObject method.
– Roknauta
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().
– Marcus Martins
Got it, I’ll post the answer.
– Roknauta
Very good, thanks for the return.
– Marcus Martins