Error: java.lang.IllegalArgumentException: id to load is required for loading

0

I am not able to save data in the database.

I created a generated id to customize the primary key in the DB. The field is called id and it is a String .

I made a test class and it is working, but when I run the program it gives the following error:

  

"java.lang.IllegalArgumentException: id to load is required for   loading "

When I save, for some reason id is null. I can not find the error. Any suggestions on why id is going null, when I click the save button? It should generate% automatic% as per the customization I made.

Follow the codes below:

Process.java

package com.damasystem.dama.model;

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

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "processo")
public class Processo implements Serializable {

    private static final long serialVersionUID = 1L;

    private String id;
    private String referenciaCliente;
    private TipoProcesso tipoProcesso;
    private Date criadoEm;
    private List<ProformaInvoiceImp> proformaInvoicesImp = new ArrayList<>();

    @Id
    @GenericGenerator(name = "processo_generator", strategy = "com.damasystem.dama.model.ProcessoCustomIdGenerator")
    @GeneratedValue(generator = "processo_generator")
    public String getId() {
        return id;
    }

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

    @Column(name = "referencia_cliente", length = 20)
    public String getReferenciaCliente() {
        return referenciaCliente;
    }

    public void setReferenciaCliente(String referenciaCliente) {
        this.referenciaCliente = referenciaCliente;
    }

    @Column(name = "tipo_processo", nullable = false, length = 10)
    public TipoProcesso getTipoProcesso() {
        return tipoProcesso;
    }

    public void setTipoProcesso(TipoProcesso tipoProcesso) {
        this.tipoProcesso = tipoProcesso;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "criado_em")
    public Date getCriadoEm() {
        return criadoEm;
    }

    public void setCriadoEm(Date criadoEm) {
        this.criadoEm = criadoEm;
    }

    @OneToMany(mappedBy = "processo", cascade = CascadeType.ALL)
    public List<ProformaInvoiceImp> getProformaInvoicesImp() {
        return proformaInvoicesImp;
    }

    public void setProformaInvoicesImp(List<ProformaInvoiceImp> proformaInvoicesImp) {
        this.proformaInvoicesImp = proformaInvoicesImp;
    }

    @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;
        Processo other = (Processo) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

}

ProcessCustomIdGenerator.java

package com.damasystem.dama.model;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

public class ProcessoCustomIdGenerator implements IdentifierGenerator {

    private Calendar calendar = Calendar.getInstance();
    private String defaultPrefix = "UNQ#" + calendar.get(Calendar.YEAR) + "-";
    private int defaultNumber = 1;

    @Override
    public Serializable generate(SessionImplementor session, Object object) throws HibernateException {

        String id = "";
        String digits = "";

        Connection connection = session.connection();

        try {
            PreparedStatement pst = connection.prepareStatement("select id from processo order by criado_em desc limit 1");
            ResultSet rs = pst.executeQuery();
            if (rs != null && rs.next()) {
                id = rs.getString("id");
                System.out.println(id);

                String anoUltimoRegistro = id.substring(4, 8);
                String anoAtual = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
                if(anoUltimoRegistro.equals(anoAtual)) {
                    String prefix = id.substring(0, 9);
                    String str[] = id.split(prefix);
                    digits = String.format("%04d", Integer.parseInt(str[1]) + 1);
                    id = prefix.concat(digits);
                } else {
                    digits = String.format("%04d", defaultNumber);
                    id = defaultPrefix.concat(digits);
                }
            } else {
                digits = String.format("%04d", defaultNumber);
                id = defaultPrefix.concat(digits);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return id;
    }

}

CadastroProcessoBean.java

package com.damasystem.dama.controller;

import java.io.Serializable;

import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import com.damasystem.dama.model.Processo;
import com.damasystem.dama.model.ProformaInvoiceImp;
import com.damasystem.dama.model.TipoProcesso;
import com.damasystem.dama.service.CadastroProcessoService;
import com.damasystem.dama.util.jsf.FacesUtil;

@Named
@ViewScoped
public class CadastroProcessoBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private Processo processo;

    private ProformaInvoiceImp proformaInvoiceImp;

    @Inject
    private CadastroProcessoService cadastroProcessoService;

    public CadastroProcessoBean() {
        limpar();
    }

    private void limpar() {
        processo = new Processo();
    }

    public void salvar() {
        this.processo = cadastroProcessoService.salvar(this.processo);
        limpar();

        FacesUtil.addInfoMessage("Processo salvo com sucesso.");
    }

    public boolean isEditando() {
        return this.processo.getId() != null;
    }

    public Processo getProcesso() {
        return processo;
    }

    public void setProcesso(Processo processo) {
        this.processo = processo;
    }

    public ProformaInvoiceImp getProformaInvoiceImp() {
        return proformaInvoiceImp;
    }

    public void setProformaInvoiceImp(ProformaInvoiceImp proformaInvoiceImp) {
        this.proformaInvoiceImp = proformaInvoiceImp;
    }

    public TipoProcesso[] getTiposProcessos() {
        return TipoProcesso.values();
    }

}

CadastroProcessoService.java

package com.damasystem.dama.service;

import java.io.Serializable;

import javax.inject.Inject;

import com.damasystem.dama.model.Processo;
import com.damasystem.dama.repository.Processos;
import com.damasystem.dama.util.jpa.Transactional;

public class CadastroProcessoService implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private Processos processos;

    @Transactional
    public Processo salvar (Processo processo) {
        Processo processoExistente = processos.porId(processo.getId());

        if(processoExistente != null && !processoExistente.equals(processo)) {
            throw new NegocioException("Ja existe um processo com a referência informada!");
        }

        return processos.guardar(processo);
    }

}

Process.java

package com.damasystem.dama.repository;

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

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceException;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.damasystem.dama.model.Processo;
import com.damasystem.dama.repository.filter.ProcessoFilter;
import com.damasystem.dama.service.NegocioException;
import com.damasystem.dama.util.jpa.Transactional;

public class Processos implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private EntityManager manager;

    public Processo guardar(Processo processo) {
        return processo = manager.merge(processo);
    }

    @Transactional
    public void remover(Processo processoSelecionado) {
        try {
            processoSelecionado = porId(processoSelecionado.getId());
            manager.remove(processoSelecionado);
            manager.flush();
        } catch (PersistenceException e) {
            throw new NegocioException("Processo não pode ser excluído.");
        }
    }

    public Processo porId(String id) {
        return manager.find(Processo.class, id);
    }

    public Processo porReferenciaCliente(String referenciaCliente) {
        try {
            return manager.createQuery("from Processo where upper(referenciaCliente) = :referenciaCliente", Processo.class)
                    .setParameter("referenciaCliente", referenciaCliente.toUpperCase())
                    .getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

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

    @SuppressWarnings("unchecked")
    public List<Processo> filtrados(ProcessoFilter filtro) {
        Session session = manager.unwrap(Session.class);
        Criteria criteria = session.createCriteria(Processo.class);

        // where like '%joao%'
        if(StringUtils.isNotBlank(filtro.getId())) {
            criteria.add(Restrictions.ilike("id", filtro.getId(), MatchMode.ANYWHERE));
        }

        // where like '%joao%'
        if(StringUtils.isNotBlank(filtro.getReferenciaCliente())) {
            criteria.add(Restrictions.ilike("referenciaCliente", filtro.getReferenciaCliente(), MatchMode.ANYWHERE));
        }

        return criteria.addOrder(Order.asc("id")).list();
    }

}

ProcessFilter.java

package com.damasystem.dama.repository.filter;

import java.io.Serializable;

public class ProcessoFilter implements Serializable {

    private static final long serialVersionUID = 1L;

    private String id;
    private String referenciaCliente;

    public String getId() {
        return id;
    }

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

    public String getReferenciaCliente() {
        return referenciaCliente;
    }

    public void setReferenciaCliente(String referenciaCliente) {
        this.referenciaCliente = referenciaCliente;
    }

}

ProcessConverter.java

package com.damasystem.dama.converter;

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

import org.apache.commons.lang3.StringUtils;

import com.damasystem.dama.model.Processo;
import com.damasystem.dama.repository.Processos;

@FacesConverter(forClass = Processo.class)
public class ProcessoConverter implements Converter {

    @Inject
    private Processos processos;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        Processo retorno = null;

        if (StringUtils.isNotEmpty(value)) {
            String id = new String(value);
            retorno = processos.porId(id);
        }

        return retorno;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value != null) {
            Processo processo = (Processo) value;
            return processo.getId() == null ? null : processo.getId().toString();
        }

        return "";
    }

}

ProcessProcess.xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:p="http://primefaces.org/ui"
                xmlns:o="http://omnifaces.org/ui"
                template="/WEB-INF/template.xhtml">

    <ui:define name="title">#{cadastroProcessoBean.editando ? 'Edição de processo' : 'Novo processo'}</ui:define>

    <ui:define name="breadcrumb">
        <li>Pages</li>
        <li>/</li>
        <li><p:link outcome="/processos/cadastroProcesso">Novo processo</p:link></li>
    </ui:define>

    <ui:define name="content">
        <f:metadata>
            <o:viewParam name="processo" value="#{cadastroProcessoBean.processo}" />
        </f:metadata>

        <h:form>
            <h1>#{cadastroProcessoBean.editando ? 'Edição de processo' : 'Novo processo'}</h1>

            <p:messages autoUpdate="true" closable="true" />

            <p:toolbar style="margin-top: 10px">
                <p:toolbarGroup>
                    <p:button value="Novo" outcome="/processos/cadastroProcesso" />
                    <p:commandButton id="botaoSalvar" value="Salvar" action="#{cadastroProcessoBean.salvar()}" update="@form" />
                </p:toolbarGroup>

                <p:toolbarGroup align="right">
                    <p:button value="Pesquisar" outcome="/processos/pesquisaProcesso" />
                </p:toolbarGroup>
            </p:toolbar>

            <p:panelGrid columns="2" id="painel"
                style="width: 100%; margin-top: 15px" columnClasses="rotulo, campo">

                <p:outputLabel value="Tipo de Processo" for="tipoProcesso" />
                <p:selectOneRadio id="tipoProcesso" value="#{cadastroProcessoBean.processo.tipoProcesso}" >
                    <f:selectItems value="#{cadastroProcessoBean.tiposProcessos}" var="tipoProcesso" 
                        itemLabel="#{tipoProcesso.descricao}" itemValue="#{tipoProcesso}" />
                </p:selectOneRadio>

                <p:outputLabel for="referenciaCliente" value="Referência do Cliente" />
                <p:inputText id="referenciaCliente" value="#{cadastroProcessoBean.processo.referenciaCliente}" size="20" maxlength="20" />

                <p:outputLabel value="Data de criação" />
                <h:outputText value="22/07/2017" />

            </p:panelGrid>
        </h:form>
    </ui:define>

</ui:composition>
    
asked by anonymous 22.07.2018 / 07:49

1 answer

0

Only to share the solution to this problem. The error was in the CadastroProcessoService class.

Where I was:

Processo processoExistente = processos.porId(processo.getId());

I replace with:

Processo processoExistente = processos.porReferenciaCliente(processo.getReferenciaCliente());

Now the code is creating a custom string as the primary key, which follows the following logic: String prefixed (UNQ #) + Current year + Sequential number. Then, when you turn the year, the sequence is restarted.

The result would be: UNQ # 2018-0001 UNQ # 2018-0002 UNQ # 2018-0003 ... UNQ # 2018-0999 UNQ # 2019-0001

I hope you can help someone else.

    
03.09.2018 / 23:11