Hibernate is not generating id to write to the bank

Asked

Viewed 81 times

0

I am handling a xls file, so far so good. I can perform setters and getters normally. however in save to go to the bank, id is coming null and with that not recording in the bank. I will post my codes to have better view.

DAO

package br.com.racionalgames.pta.dao;

import br.com.racionalgames.pta.model.UploadFiles;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

@Repository("uploadFile")
@Transactional
@EnableTransactionManagement
public class UploadFileDAOImpl implements UploadFileDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void saveFile(UploadFiles upload) throws Exception {

        try {

            Query query = sessionFactory.getCurrentSession()
                    .createSQLQuery("INSERT INTO criterios_multiskill (documento, nome, empresa_cliente, empresa_assessoria, carteira, produto, tipo_operacao, tipo_pessoa, grupo, acao, descricao, criado_em, criado_por) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
                    .setParameter(0, upload.getId())
                    .setParameter(1, upload.getDocumento())
                    .setParameter(2, upload.getNomeOperador())
                    .setParameter(3, upload.getEmpresaCliente())
                    .setParameter(4, upload.getEmpresaAssessoria())
                    .setParameter(5, upload.getCarteira())
                    .setParameter(6, upload.getProduto())
                    .setParameter(7, upload.getTipoOperacao())
                    .setParameter(8, upload.getTipoPessoa())
                    .setParameter(9, upload.getGrupo())
                    .setParameter(10, upload.getAcao())
                    .setParameter(11, upload.getDescricao())
                    .setParameter(12, upload.getCriadoEm())
                    .setParameter(13, upload.getCriadoPor());

            query.executeUpdate();

        } catch (Exception e) {

            e.printStackTrace();
        }

    }

}

/BEAN/

package br.com.racionalgames.pta.mbean;

import br.com.racionalgames.pta.model.UploadFiles;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Scanner;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.servlet.http.Part;
import br.com.racionalgames.pta.dao.UploadFileDAO;

@SessionScoped
@ManagedBean(name = "uploadFile")

public class UploadFileMBean {

    private UploadFiles fileUpload = new UploadFiles();

    @ManagedProperty(value = "#{uploadFileDAO}")
    private UploadFileDAO uploadFileDAO;

    public UploadFileDAO getUploadFileDAO() {
        return uploadFileDAO;
    }

    public void setUploadFileDAO(UploadFileDAO uploadFileDAO) {
        this.uploadFileDAO = uploadFileDAO;
    }

    private Part arquivo;

    public UploadFiles getFileUpload() {
        return fileUpload;
    }

    public void setFileUpload(UploadFiles fileUpload) {
        this.fileUpload = fileUpload;
    }

    public Part getArquivo() {
        return arquivo;
    }

    public void setArquivo(Part arquivo) {
        this.arquivo = arquivo;
    }

    public void upload() throws IOException, Exception {

        Date data = new Date(System.currentTimeMillis());

        Scanner scan = new Scanner(arquivo.getInputStream(), "UTF-8");

        while (scan.hasNext()) {
            String linha = scan.nextLine();

            if (linha != null && !linha.trim().isEmpty()) {

                String[] dados = linha.split("\\;");

                fileUpload.setDocumento(dados[0]);
                fileUpload.setNomeOperador(dados[1]);
                fileUpload.setEmpresaCliente(dados[2]);
                fileUpload.setEmpresaAssessoria(dados[3]);
                fileUpload.setCarteira(dados[4]);
                fileUpload.setProduto(dados[5]);
                fileUpload.setTipoOperacao(dados[6]);
                fileUpload.setTipoPessoa(dados[7]);
                fileUpload.setGrupo(dados[8]);
                fileUpload.setAcao(dados[9]);
                fileUpload.setDescricao("sandro");
                fileUpload.setCriadoEm(data);
                fileUpload.setCriadoPor(1);

                uploadFileDAO.saveFile(fileUpload);

            }
        }
    }

    public byte[] toByteArrayUsingJava(InputStream is) throws Exception {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int reads = is.read();

        while (reads != -1) {

            baos.write(reads);
            reads = is.read();
        }

        return baos.toByteArray();

    }
}

/INTERFACE/

package br.com.racionalgames.pta.dao;

import br.com.racionalgames.pta.model.UploadFiles;

public interface UploadFileDAO {

    public void saveFile(UploadFiles upload) throws Exception;

}

/OBJECT/

package br.com.racionalgames.pta.model;

import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "criterios_multiskill", catalog = "pta")
public class UploadFiles implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "documento")
    private String documento;

    @Column(name = "nome")
    private String nomeOperador;

    @Column(name = "empresa_cliente")
    private String empresaCliente;

    @Column(name = "empresa_assessoria")
    private String empresaAssessoria;

    @Column(name = "carteira")
    private String carteira;

    @Column(name = "produto")
    private String produto;

    @Column(name = "tipo_operacao")
    private String tipoOperacao;

    @Column(name = "tipo_pessoa")
    private String tipoPessoa;

    @Column(name = "grupo")
    private String grupo;

    @Column(name = "acao")
    private String acao;

    @Column(name = "descricao")
    private String descricao;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "criado_em")
    private Date criadoEm;

    @Column(name = "criado_por")
    private Integer criadoPor;
    @Lob
    private byte[] arquivo;

    public UploadFiles() {

    }

    public Integer getId() {
        return id;
    }

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

    public byte[] getArquivo() {
        return arquivo;
    }

    public void setArquivo(byte[] arquivo) {
        this.arquivo = arquivo;
    }

    public String getDocumento() {
        return documento;
    }

    public void setDocumento(String documento) {
        this.documento = documento;
    }

    public String getNomeOperador() {
        return nomeOperador;
    }

    public void setNomeOperador(String nome) {
        this.nomeOperador = nome;
    }

    public String getEmpresaCliente() {
        return empresaCliente;
    }

    public void setEmpresaCliente(String empresaCliente) {
        this.empresaCliente = empresaCliente;
    }

    public String getEmpresaAssessoria() {
        return empresaAssessoria;
    }

    public void setEmpresaAssessoria(String empresaAssessoria) {
        this.empresaAssessoria = empresaAssessoria;
    }

    public String getCarteira() {
        return carteira;
    }

    public void setCarteira(String carteira) {
        this.carteira = carteira;
    }

    public String getProduto() {
        return produto;
    }

    public void setProduto(String produto) {
        this.produto = produto;
    }

    public String getTipoOperacao() {
        return tipoOperacao;
    }

    public void setTipoOperacao(String tipoOperacao) {
        this.tipoOperacao = tipoOperacao;
    }

    public String getTipoPessoa() {
        return tipoPessoa;
    }

    public void setTipoPessoa(String tipoPessoa) {
        this.tipoPessoa = tipoPessoa;
    }

    public String getGrupo() {
        return grupo;
    }

    public void setGrupo(String grupo) {
        this.grupo = grupo;
    }

    public String getAcao() {
        return acao;
    }

    public void setAcao(String acao) {
        this.acao = acao;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public Date getCriadoEm() {
        return criadoEm;
    }

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

    public Integer getCriadoPor() {
        return criadoPor;
    }

    public void setCriadoPor(Integer criadoPor) {
        this.criadoPor = criadoPor;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 29 * hash + Objects.hashCode(this.id);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final UploadFiles other = (UploadFiles) obj;
        if (!Objects.equals(this.id, other.id)) {
            return false;
        }
        return true;
    }

}

/VIEW XHTML/

<!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:h="http://java.sun.com/jsf/html"      
      xmlns:ui="http://java.sun.com/jsf/facelets"      
      xmlns:p="http://primefaces.org/ui"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <ui:composition template="/WEB-INF/inc/template.xhtml">
        <ui:define name="titulo">
            <h:outputText value=" - Home" />
        </ui:define>
        <ui:define name="conteudo">
            <div class='wrp-content'>
                <p:panelGrid columns="1">
                    <h:form style="margin-top: 100px" enctype="multipart/form-data">
                        <h:outputLabel value="Selecione o arquivo:" for="arquivo" />
                        <br />
                        <br />
                        <h:inputFile                             
                            id="arquivo"
                            required="true"                            
                            value="#{uploadFile.arquivo}"
                            requiredMessage="Informe o arquivo" />
                        <h:message for="arquivo" />
                        <br />
                        <br />
                        <h:outputLabel value="Descricao do arquivo:" for="descricao" />
                        <br />
                        <br />                      
                        <p:inputTextarea
                            id="descricao"
                            value="#{uploadFile.fileUpload.descricao}"
                            cols="50"
                            required="true"
                            requiredMessage="Descricao obrigatoria"
                            rows="5"
                            styleClass="inputAvNome input-padrao">
                        </p:inputTextarea>
                        <h:message for="descricao" />
                        <br />
                        <br />
                        <p:commandButton ajax="false" value="Enviar" action="#{uploadFile.upload()}" style="background-color:#87CEFA">
                            <f:ajax execute="@form" render="@all"></f:ajax>
                        </p:commandButton>
                        <p:commandButton  
                            ajax="false"
                            action="home" 
                            value="Cancelar" 
                            style="background-color:red">
                        </p:commandButton>
                    </h:form>
                </p:panelGrid>
            </div>
        </ui:define>
    </ui:composition>
</html>
  • didn’t quite understand the error ? You are trying to save and you are giving error because the ID is null ?

  • this, when I call query.executeUpdate(); it drops in catch with the following sqlgrammarexception error could not Extract

  • Which bank? The bank is ready for the automated increment?.

  • The database is Mysql, it is a project that is already in production, however I just entered it. I go into debug mode and even show the data in get, but when executing the query falls in catch with this excerpt

1 answer

0

Switch this to GenerationType.AUTO:

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

Take a look at Mysql if the ID is auto AUTO_INCREMENT.

Browser other questions tagged

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