Pessoal estou com um problema, alguem pode me ajudar?
Tenho 2 classes e preciso relacionar.
Só que no meu view estou precisando fazer o Converter, ja tentei varios e não consegui.
Alguem que tiver um Converter que funcione e poder me ajudar eu agradeço.
Aguardo suas respostas.
Beijos
Converter[RESOLVIDO]
8 Respostas
Vc vai precisar ser um pouco mais especifica na sua dificuldade do momento…
Neste modelo na hora de Salvar ele dar um erro Indice -1, ja tentei de tudo se você poder me ajudar ficarei muito grata.
Classe Bairro
@Entity
public class Bairro implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String nome;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + this.id;
hash = 83 * hash + Objects.hashCode(this.nome);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Bairro other = (Bairro) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.nome, other.nome)) {
return false;
}
return true;
}
Classe Usuario
@Entity
public class Usuario implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String nome;
@ManyToOne
private Bairro bairro;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Bairro getBairro() {
return bairro;
}
public void setBairro(Bairro bairro) {
int i = 0;
int num = Integer.parseInt(String.valueOf(i));
}
@Override
public int hashCode() {
int hash = 7;
hash = 47 * hash + (int) (this.id ^ (this.id >>> 32));
hash = 47 * hash + Objects.hashCode(this.nome);
hash = 47 * hash + Objects.hashCode(this.bairro);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Usuario other = (Usuario) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.nome, other.nome)) {
return false;
}
if (!Objects.equals(this.bairro, other.bairro)) {
return false;
}
return true;
}
Este é a classe Converter
@Override
public String getAsString(FacesContext context, UIComponent component,
Object value) throws ConverterException {
List<Object> items = this.getSelectItems(component);
int index = items.indexOf(value);
return String.valueOf(index);
}
/**
* Obtem o SelecItem de acordo com a opção selecionada pelo usuário
*/
protected Object getSelectedItemByIndex(UIComponent component, int index) {
List<Object> items = this.getSelectItems(component);
int size = items.size();
if (index > -1 && size > index) {
return items.get(index);
}
return null;
}
protected List<Object> getSelectItems(UIComponent component) {
List<Object> items = new ArrayList<Object>();
int childCount = component.getChildCount();
if (childCount == 0) {
return items;
}
List<UIComponent> children = component.getChildren();
for (UIComponent child : children) {
if (child instanceof UISelectItem) {
this.addSelectItem((UISelectItem) child, items);
} else if (child instanceof UISelectItems) {
this.addSelectItems((UISelectItems) child, items);
}
}
return items;
}
protected void addSelectItem(UISelectItem uiItem, List<Object> items) {
boolean isRendered = uiItem.isRendered();
if (!isRendered) {
items.add(null);
return;
}
Object value = uiItem.getValue();
SelectItem item;
if (value instanceof SelectItem) {
item = (SelectItem) value;
} else {
Object itemValue = uiItem.getItemValue();
String itemLabel = uiItem.getItemLabel();
// JSF throws a null pointer exception for null values and labels,
// which is a serious problem at design-time.
item = new SelectItem(itemValue == null ? "" : itemValue,
itemLabel == null ? "" : itemLabel, uiItem.getItemDescription(),
uiItem.isItemDisabled());
}
items.add(item);
}
@SuppressWarnings("unchecked")
protected void addSelectItems(UISelectItems uiItems, List<Object> items) {
boolean isRendered = uiItems.isRendered();
if (!isRendered) {
items.add(null);
return;
}
Object value = uiItems.getValue();
if (value instanceof SelectItem) {
items.add(value);
} else if (value instanceof Object[]) {
Object[] array = (Object[]) value;
for (int i = 0; i < array.length; i++) {
if (array[i] instanceof SelectItemGroup) {
this.resolveAndAddItems((SelectItemGroup) array[i], items);
} else {
items.add(array[i]);
}
}
} else if (value instanceof Collection) {
Iterator<Object> iter = ((Collection<Object>) value).iterator();
Object item;
while (iter.hasNext()) {
item = iter.next();
if (item instanceof SelectItemGroup) {
this.resolveAndAddItems((SelectItemGroup) item, items);
} else {
items.add(item);
}
}
} else if (value instanceof Map) {
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) value)
.entrySet()) {
Object label = entry.getKey();
SelectItem item = new SelectItem(entry.getValue(),
label == null ? (String) null : label.toString());
if (item instanceof SelectItemGroup) {
this.resolveAndAddItems((SelectItemGroup) item, items);
} else {
items.add(item);
}
}
}
}
protected void resolveAndAddItems(SelectItemGroup group, List<Object> items) {
for (SelectItem item : group.getSelectItems()) {
if (item instanceof SelectItemGroup) {
this.resolveAndAddItems((SelectItemGroup) item, items);
} else {
items.add(item);
}
}
}
Bean Usuario
@ManagedBean(name = "UsuarioBean")
@SessionScoped
public class UsuarioBean implements Serializable {
private Usuario usuario;
private UsuarioDaoImp dao;
List<Usuario> usuarios = new ArrayList<>();
public UsuarioBean(){
usuario = new Usuario();
usuarios = new UsuarioDaoImp().listar();
dao = new UsuarioDaoImp();
}
public String cadastrar() throws NoSuchAlgorithmException, AddressException {
dao.cadastrar(usuario);
usuarios = new UsuarioDaoImp().listar();
usuario = new Usuario();
return "voltar";
}
public String criptografaSenha(String senha) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
BigInteger hash = new BigInteger(1, md.digest(senha.getBytes()));
String s = hash.toString(16);
if (s.length() % 2 != 0) {
s = "0" + s;
}
return s;
}
private boolean validaCPF(String strCpf) {
int iDigito1Aux = 0, iDigito2Aux = 0, iDigitoCPF;
int iDigito1 = 0, iDigito2 = 0, iRestoDivisao = 0;
String strDigitoVerificador, strDigitoResultado;
if (!strCpf.substring(0, 1).equals("")) {
try {
strCpf = strCpf.replace('.', ' ');
strCpf = strCpf.replace('-', ' ');
strCpf = strCpf.replaceAll(" ", "");
for (int iCont = 1; iCont < strCpf.length() - 1; iCont++) {
iDigitoCPF = Integer.valueOf(strCpf.substring(iCont - 1, iCont)).intValue();
iDigito1Aux = iDigito1Aux + (11 - iCont) * iDigitoCPF;
iDigito2Aux = iDigito2Aux + (12 - iCont) * iDigitoCPF;
}
iRestoDivisao = (iDigito1Aux % 11);
if (iRestoDivisao < 2) {
iDigito1 = 0;
} else {
iDigito1 = 11 - iRestoDivisao;
}
iDigito2Aux += 2 * iDigito1;
iRestoDivisao = (iDigito2Aux % 11);
if (iRestoDivisao < 2) {
iDigito2 = 0;
} else {
iDigito2 = 11 - iRestoDivisao;
}
strDigitoVerificador = strCpf.substring(strCpf.length() - 2, strCpf.length());
strDigitoResultado = String.valueOf(iDigito1) + String.valueOf(iDigito2);
return strDigitoVerificador.equals(strDigitoResultado);
} catch (Exception e) {
return false;
}
} else {
return false;
}
}
public boolean validEmail(String email) {
Pattern p = Pattern.compile("^[\\w-]+(\\.[\\w-]+)*@([\\w-]+\\.)+[a-zA-Z]{2,7}$");
Matcher m = p.matcher(email);
if (m.find()) {
return true;
} else {
return false;
}
}
public void enviarEmailConfirmação(String email) throws AddressException {
String destino = email;
String remetente = "[email removido]";
String host = "localhost";
Properties propriedades = System.getProperties();
propriedades.setProperty("smtp.gmail.com", host);
Session session = Session.getDefaultInstance(propriedades);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(remetente));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
message.setSubject("This is the Subject Line!");
message.setContent("<h1>This is actual message</h1>", "text/html");
Transport.send(message);
System.out.println("E-mail enviado com sucesso.");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public List<Usuario> getUsuarios() {
return usuarios;
}
public void setUsuarios(List<Usuario> usuarios) {
this.usuarios = usuarios;
}
View
<h:form prependId="false" id="cadastroUsuario">
<p:panel header="Cadastro de Usuários" style="width: 700px;margin-left: 24%;">
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="Nome: "/>
<h:inputText id="nome" value="#{UsuarioBean.usuario.nome}" size="40" maxlength="50" autocomplete="off" required="true" requiredMessage="Campo Nome é Obrigatório"/>
<h:outputText value="Bairro:" />
<h:selectOneMenu onclick="mensage();" converter="objectConverter" id="sele1" value="#{UsuarioBean.usuario.bairro}" required="true" requiredMessage="Campo Bairro Obrigatorio">
<f:selectItems value="#{BairroBean.bairros}" var="lisBairro" itemLabel="#{lisBairro.nome}" itemValue="#{lisBairro.id}"/>
</h:selectOneMenu>
<p:commandButton immediate="true" ajax="false" value="Voltar" action="voltar" style="background: #999999; color: #ffffff; " icon="ui-icon-back" />
<p:commandButton ajax="false" value="Cadastrar" update="cadastroUsuario" actionListener="#{UsuarioBean.cadastrar()}" style="background: #999999; color: #ffffff; " icon="ui-icon-disk" />
</h:panelGrid>
</p:panel>
</h:form>
Adicionou o converter no faces-config?
ps: Acredito que no converter vá apenas os métodos getAsObject e getAsString e no bean você cria um select item.
algo tipo
public List<SelectItem> getSelectItemBairros(){
try{
List<Bairro> lista = bairroDAO.listar();
List<SelectItem> listaItens = new ArrayList<SelectItem>();
listaItens.add(new SelectItem("","Selecione"));
for(Bairro b: lista)
listaItens.add(new SelectItem(b.getId(),b.getNome()));
return listaItens;
}catch(Exception e){
//
}
return null;
}
Não adcionei no faces-config coloquei como annotation na classe do converter @FacesConverter(value = “objectConverter”)
Mostre o getAsObject da sua classe converter e o stacktrace do erro.
Não sei muito bem qual sua dúvida na coisa toda, mas aqui tem um exemplo de utilização de converter: http://www.guj.com.br/188-campo-sempre-invalido-selectonemenu/#answer-330
Se a dúvida não for sanada ali, tente elaborar mais
E poste o getAsObject do seu converter também?
Obrigado gente, este exemplo que Rodrigo Sasaki postou funcionou perfeitamente.
Muito grata.
Opa, bom saber 