Erro de validação de NULL

1 resposta Resolvido
java
R

Galera, estou com um projeto em andamento que foi feito por outra pessoa, porém ao tentar realizar o cadastro de alguma coisa estou recebendo o erro:

Duplicate annotation for class: interface javax.validation.constraints.NotNull: javax.validation.constraints.NotNull(message={javax.validation.constraints.NotNull.message}, groups=[], payload=[])

E estou nisso o dia todo e nem consegui descobrir o motivo disso.
Se alguém puder dar uma força ai, agradeço
Está faltando o @ em algumas partes do código porque o GUJ interpreta como mencionar usuário.

Segue abaixo o código da aplicação referente a essa parte do erro:
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:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui"
      xmlns:f="http://java.sun.com/jsf/core">
<ui:composition id="composicao" template="/template.xhtml">
    <!--   <ui:define name="title">
          <h:outputText value="#{bundle.CreateAreasTitle}"> </h:outputText>
      </ui:define> -->
    <ui:define name="body">


        <f:view>
            <f:metadata>
                <f:viewParam name="codigo" value="#{areasController.selected}" />
            </f:metadata>

            <h:outputScript name="js/locale-primefaces.js"/>
            <h:outputScript name="js/jquery.maskMoney.js"/>

            <script  type="text/javascript">
                $(document).ready(format);
                function format() {

                }
            </script>

            <ui:include src="/pagina/metaBaseAtivos/Modal.xhtml">
                <ui:param name="editar" value="true" />
                <ui:param name="comando" value="#{areasController.selecionarMetaBaseAtivosList}"   />
            </ui:include>

            <ui:include src="/pagina/cr/Modal.xhtml">
                <ui:param name="editar" value="true" />
                <ui:param name="comando" value="#{areasController.selecionarCrList}"   />
            </ui:include>


            <h:form id="form">
                <p:panel styleClass="centralizado"  header="#{bundle.CreateAreasTitle}"  style="margin-top: 10px; width: 1024px;">

                    <f:facet name="actions">  
                        <p:commandLink onclick="PF('dlgHelp').show();" styleClass="ui-panel-titlebar-icon ui-corner-all ui-state-default">  
                            <h:outputText styleClass="ui-icon ui-icon-help" />  
                        </p:commandLink>  
                    </f:facet>                 

                    <h:panelGrid width="100%" columnClasses="colunaTabela1,colunaTabela2" columns="2">
                       <h:outputLabel value="#{bundle.CreateAreasLabel_area}" for="area" />
                       <p:inputText id="area"   maxlength="255"   value="#{areasController.selected.area}" title="#{bundle.CreateAreasTitle_area}" required="true" requiredMessage="Informe a Área" />
                      
                    </h:panelGrid>
                    
                </p:panel>
                <p:panel styleClass="centralizado" header="#{bundle.acoes}" style="margin-top: 10px; width: 1024px;">
                    <h:panelGrid style="text-align: center" columns="3" width="100%">    
                        <p:commandButton id="botaoSalvar" icon="ui-icon-disk" action="#{areasController.create}" value="#{bundle.CreateAreasSaveLink}" ajax="false" />
                        <p:commandButton id="botaoConsultar" icon="ui-icon-search" action="#{areasController.prepareList}" value="#{bundle.CreateAreasShowAllLink}" ajax="false" immediate="true"/>
                        <p:commandButton id="botaoNovo" icon="ui-icon-document"  value="#{bundle.novo}" action="#{areasController.prepareCreate}" ajax="false" immediate="true"/>
                    </h:panelGrid>
                </p:panel>            
            </h:form>

            <p:dialog id="modalHelp" header="Ajuda" widgetVar="dlgHelp" resizable="false" modal="true" >                 
                <h:outputText escape="false" value="{ajuda.ajuda}" />
            </p:dialog>

        </f:view>
    </ui:define>
</ui:composition>

Controller:

package br.com.celg.controlado;

import br.com.celg.entidade.Areas;

import br.com.celg.controlado.util.AbstractController;

import br.com.celg.controlado.util.JsfUtil;

import br.com.celg.controlado.util.PaginationHelper;

import br.com.celg.sessao.interfaceFacade.AreasFacadeLocal;
import java.util.ArrayList;

import java.util.List;

import java.io.Serializable;

import java.io.ByteArrayOutputStream;

import javax.servlet.http.HttpServletResponse;

import java.io.OutputStream;

import java.util.ResourceBundle;

import javax.annotation.PostConstruct;

import javax.ejb.EJB;

import javax.faces.bean.ManagedBean;

import javax.faces.bean.ViewScoped;

import javax.faces.component.UIComponent;

import javax.faces.context.FacesContext;

import javax.faces.convert.Converter;

import javax.faces.convert.FacesConverter;

import javax.faces.model.DataModel;

import javax.faces.model.ListDataModel;

import javax.faces.model.SelectItem;
ManagedBean(name = areasController)

ViewScoped

public class AreasController extends AbstractController implements Serializable {
private Areas current;
EJB
private br.com.celg.sessao.interfaceFacade.AreasFacadeLocal ejbFacade;

Override
public SelectItem[] getSelectItemsConsulta() {
    SelectItem[] itemsLocal = new SelectItem[4];
    itemsLocal[0] = new SelectItem("id", ResourceBundle.getBundle("/Bundle").getString("CreateAreasTitle_id"));
    itemsLocal[1] = new SelectItem("area", ResourceBundle.getBundle("/Bundle").getString("CreateAreasTitle_area"));
    itemsLocal[2] = new SelectItem("metaBaseAtivosList", ResourceBundle.getBundle("/Bundle").getString("CreateAreasTitle_metaBaseAtivosList"));
    itemsLocal[3] = new SelectItem("crList", ResourceBundle.getBundle("/Bundle").getString("CreateAreasTitle_crList"));
    return itemsLocal;
}

public AreasController() {
}

private List<Areas> listaAreas;

public List<Areas> getListaAreas() {
    return listaAreas;
}

public void setListaAreas(List<Areas> listaAreas) {
    this.listaAreas = listaAreas;
}

PostConstruct
public void inicializarLista() {
    listaAreas = ejbFacade.findAll();
}


public Areas getSelected() {
    if (current == null) {
        current = new Areas();
        selectedItemIndex = -1;
    }
    return current;
}

public void setSelected(Areas entidade) {
    this.current = entidade;
}

public void selecionarMetaBaseAtivosList() {
    try {
        br.com.celg.entidade.MetaBaseAtivos objeto = (br.com.celg.entidade.MetaBaseAtivos) FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("item");
        getSelected().getMetaBaseAtivosList().add(objeto);
    } catch (Exception e) {
        JsfUtil.addErrorMessage(e, e.getMessage());
    }
}

public void removerMetaBaseAtivosList() {
    try {
        br.com.celg.entidade.MetaBaseAtivos objeto = (br.com.celg.entidade.MetaBaseAtivos) FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("item");
        getSelected().getMetaBaseAtivosList().remove(objeto);
    } catch (Exception e) {
        JsfUtil.addErrorMessage(e, e.getMessage());
    }
}

public void selecionarCrList() {
    try {
        br.com.celg.entidade.Cr objeto = (br.com.celg.entidade.Cr) FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("item");
        getSelected().getCrList().add(objeto);
    } catch (Exception e) {
        JsfUtil.addErrorMessage(e, e.getMessage());
    }
}

public void removerCrList() {
    try {
        br.com.celg.entidade.Cr objeto = (br.com.celg.entidade.Cr) FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("item");
        getSelected().getCrList().remove(objeto);
    } catch (Exception e) {
        JsfUtil.addErrorMessage(e, e.getMessage());
    }
}

private AreasFacadeLocal getFacade() {
    return ejbFacade;
}

public PaginationHelper getPagination() {
    if (pagination == null) {
        pagination = new PaginationHelper(10) {
            Override
            public int getItemsCount() throws Exception {
                //return getFacade().count(getConsultarPor(), getParametroConsulta());
                return getFacade().count();
            }

            Override
            public DataModel createPageDataModel() throws Exception {
                return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                //return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, getConsultarPor(), getParametroConsulta()));
            }
        };
    }
    return pagination;
}

public String prepareView() {
    current = (Areas) getItems().getRowData();
    selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
    return "View";
}

public String prepareCreate() {
    current = new Areas();
    selectedItemIndex = -1;
    return "Create";
}


public String create() {
    try {
        getFacade().create(current);
        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AreasCreated"));
        return prepareCreate();
    } catch (Exception e) {
        JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        return null;
    }
}

public String prepareEdit() {
    current = (Areas) getItems().getRowData();
    selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
    return "Edit";
}

public String update() {
    try {
        getFacade().edit(current);
        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AreasUpdated"));
        return "View";
    } catch (Exception e) {
        JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        return null;
    }
}

public String destroy() {
    current = (Areas) getItems().getRowData();
    selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
    performDestroy();
    recreateModel();
    return "List";
}

public String destroyAndView() {
    performDestroy();
    recreateModel();
    updateCurrentItem();
    if (selectedItemIndex >= 0) {
        return "View";
    } else {
        // all items were removed - go back to list
        recreateModel();
        return "List";
    }
}

private void performDestroy() {
    try {
        getFacade().remove(current);
        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AreasDeleted"));
    } catch (Exception e) {
        JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
    }
}

private void updateCurrentItem() {
    int count = getFacade().count();
    if (selectedItemIndex >= count) {
        // selected index cannot be bigger than number of items:
        selectedItemIndex = count - 1;
        // go to previous page if last page disappeared:
        if (pagination.getPageFirstItem() >= count) {
            pagination.previousPage();
        }
    }
    if (selectedItemIndex >= 0) {
        current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
    }
}

Override
public void consultar() {
    try {
        //getPagination().getItemsCount();
        items = getPagination().createPageDataModel();
    } catch (Exception ex) {
        JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("OcorreuErro"));
    }
}

public void next() {
    try {
        getPagination().nextPage();
        items = getPagination().createPageDataModel();
    } catch (Exception ex) {
        JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("OcorreuErro"));
    }
}

public void previous() {
    try {
        getPagination().previousPage();
        items = getPagination().createPageDataModel();
    } catch (Exception ex) {
        JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("OcorreuErro"));
    }

}

public void inicio() {
    try {
        getPagination().startPage();
        items = getPagination().createPageDataModel();
    } catch (Exception ex) {
        JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("OcorreuErro"));
    }

}

public void fim() {
    try {
        getPagination().endPage();
        items = getPagination().createPageDataModel();
    } catch (Exception ex) {
        JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("OcorreuErro"));
    }

}

public SelectItem[] getItemsAvailableSelectMany() {
    return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}

public SelectItem[] getItemsAvailableSelectOne() {
    return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}

public List<Areas> complete(String query) {
    List<Areas> results = new ArrayList<Areas>();
    return results;
}

public void gerarRelatorio() {
    try {


        ByteArrayOutputStream baos = null;
        //JsfUtil.relatorio(null, null, new int[]{3, 10, 6, 6, 3, 3, 3, 4}, null, null);

        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setContentType("application/pdf");
//            response.setContentType(application/force-download);

response.setContentLength(baos.size());

OutputStream os = response.getOutputStream();

baos.writeTo(os);

os.flush();

os.close();
} catch (Exception ex) {
        JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("OcorreuErro"));
    }
}

FacesConverter(forClass = Areas.class)
public static class AreasControllerConverter implements Converter {

    Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        if (value == null || value.length() == 0 || value.equals("null")) {
            return null;
        }
        AreasController controller = (AreasController) facesContext.getApplication().getELResolver().
                getValue(facesContext.getELContext(), null, "areasController");
        return controller.ejbFacade.find(getKey(value));
    }

    java.math.BigDecimal getKey(String value) {
        java.math.BigDecimal key;
        key = new java.math.BigDecimal(value);
        return key;
    }

    String getStringKey(java.math.BigDecimal value) {
        StringBuffer sb = new StringBuffer();
        sb.append(value);
        return sb.toString();
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof Areas) {
            Areas o = (Areas) object;
            return getStringKey(o.getId());
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + AreasController.class.getName());
        }
    }
}

FacesConverter(value = "AreasConverter")
public static class AreasController2Converter implements Converter {

    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        if (value == null || value.length() == 0 || value.equals("null")) {
            return null;
        }
        AreasController controller = (AreasController) facesContext.getApplication().getELResolver().
                getValue(facesContext.getELContext(), null, "areasController");
        return controller.ejbFacade.find(getKey(value));
    }

    java.math.BigDecimal getKey(String value) {
        java.math.BigDecimal key;
        key = new java.math.BigDecimal(value);
        return key;
    }

    String getStringKey(java.math.BigDecimal value) {
        StringBuffer sb = new StringBuffer();
        sb.append(value);
        return sb.toString();
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof Areas) {
            Areas o = (Areas) object;
            return getStringKey(o.getId());
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + AreasController.class.getName());
        }
    }
}

}

Entidade:

/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */
    package br.com.celg.entidade;
import java.io.Serializable;

import java.math.BigDecimal;

import java.util.List;

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import <a href="http://javax.persistence.Id">javax.persistence.Id</a>;

import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;

import javax.persistence.OneToMany;

import javax.persistence.Table;

import javax.validation.constraints.NotNull;

import javax.validation.constraints.Size;

import javax.xml.bind.annotation.XmlRootElement;

import javax.xml.bind.annotation.XmlTransient;

/**
*

  • author paulo
    
    */
    
    Entity
    
    Table(name = AREAS)
    
    XmlRootElement
    
    NamedQueries({
    
    NamedQuery(name = Areas.findAll, query = SELECT a FROM Areas a),
    
    NamedQuery(name = Areas.findById, query = SELECT a FROM Areas a WHERE <a href="http://a.id">a.id</a> = :id),
    
    NamedQuery(name = Areas.findByArea, query = SELECT a FROM Areas a WHERE a.area = :area)})
    
    public class Areas implements Serializable {
    
    private static final long serialVersionUID = 1L;
    
    // Max(value=?)  Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
    
    Id
    
    Basic(optional = false)
    
    NotNull
    
    Column(name = ID)
    
    private BigDecimal id;
    
    Size(max = 255)
    
    Column(name = AREA)
    
    private String area;
    
    OneToMany(mappedBy = idArea)
    
    private List metaBaseAtivosList;
    
    OneToMany(mappedBy = idArea)
    
    private List crList;
    

    public Areas() {
    }

    public Areas(BigDecimal id) {
    
    <a href="http://this.id">this.id</a> = id;
    
    }
    
    public BigDecimal getId() {
    
    return id;
    
    }
    
    public void setId(BigDecimal id) {
    
    <a href="http://this.id">this.id</a> = id;
    
    }
    
    public String getArea() {
    
    return area;
    
    }
    
    public void setArea(String area) {
    
    this.area = area;
    
    }
    
    XmlTransient
    
    public List getMetaBaseAtivosList() {
    
    return metaBaseAtivosList;
    
    }
    
    public void setMetaBaseAtivosList(List metaBaseAtivosList) {
    
    this.metaBaseAtivosList = metaBaseAtivosList;
    
    }
    
    XmlTransient
    
    public List getCrList() {
    
    return crList;
    
    }
    
    public void setCrList(List crList) {
    
    this.crList = crList;
    
    }
    
    Override
    
    public int hashCode() {
    
    int hash = 0;
    
    hash += (id != null ? id.hashCode() : 0);
    
    return hash;
    
    }
    
    Override
    
    public boolean equals(Object object) {
    
    // TODO: Warning - this method won’t work in the case the id fields are not set
    
    if (!(object instanceof Areas)) {
    
    return false;
    
    }
    
    Areas other = (Areas) object;
    
    if ((<a href="http://this.id">this.id</a> == null && <a href="http://other.id">other.id</a> != null) || (<a href="http://this.id">this.id</a> != null && !this.id.equals(<a href="http://other.id">other.id</a>))) {
    
    return false;
    
    }
    
    return true;
    
    }
    
    Override
    
    public String toString() {
    
    return br.com.celg.entidade.Areas[ id= + id + " ]";
    
    }
    

}

Facade:

/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */
    package br.com.celg.sessao;
import br.com.celg.entidade.Areas;

import br.com.celg.sessao.interfaceFacade.AreasFacadeLocal;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

/**
*

  • author paulo
    
    */
    
    Stateless
    
    public class AreasFacade extends AbstractFacade implements AreasFacadeLocal {
    
    PersistenceContext(unitName = SGT-SGIPU)
    
    private EntityManager em;
    
    Override
    
    protected EntityManager getEntityManager() {
    
    return em;
    
    }
    
    public AreasFacade() {
    
    super(Areas.class);
    
    }
    

}

Interface:

/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */
    package br.com.celg.sessao.interfaceFacade;
import br.com.celg.entidade.Areas;

import java.util.List;

import javax.ejb.Local;

/**
*

  • author paulo
    */
    Local
    public interface AreasFacadeLocal {

    void create(Areas areas);

    void edit(Areas areas);

    void remove(Areas areas);

    Areas find(Object id);

    List findAll();

    List findRange(int[] range);

    int count();

}

1 Resposta

R
Solucao aceita

Já resolvi o problema, se alguém estiver passando pelo mesmo, basta apenas tirar o @NotNull na Entidade.

Criado 9 de janeiro de 2018
Ultima resposta 9 de jan. de 2018
Respostas 1
Participantes 1