5
respostas

inserção no mysql

Estou inserindo pelo hibernate os campos de um objeto Mercado e pela notação: @OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL) private List categorias; o id que está como foreign key no mercado para a tabela categoria, quando tento inserir ele dá esse erro: 2019-09-11 01:09:58 WARN SqlExceptionHelper:129 - SQL Error: 1364, SQLState: HY000 2019-09-11 01:09:58 ERROR SqlExceptionHelper:131 - Field 'id_catpro' doesn't have a default value 2019-09-11 01:10:00 ERROR MercadoDAO:53 - could not execute statement

está pedindo na pk um default value, sendo que esse atributo é uma sequence, como posso resolver isso no mysql sem perder a sequence da pk?

5 respostas

Olá Fernando!

Poderia mandar seu código para eu dar uma olhada por favor?

Olá Fernando!

Conseguiu resolver o problema?

Classe mercado ` package br.com.fractal.mercado.entity;

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

import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table;

@Entity @Table(name = "mercado") public class Mercado implements Serializable {

private static final long serialVersionUID = 3651127774133107117L;

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

@Column(name = "cnpj_merc", nullable = true)
private String cnpj;

@Column(name = "nome_fantasia_merc", nullable = true)
private String nomeFantasia;

@Column(name = "nome_merc", nullable = true)
private String nome;

@Column(name = "end_merc", nullable = true)
private String end;

@Column(name = "bairro_merc", nullable = true)
private String bairro;

@Column(name = "cep_merc", nullable = true)
private String cep;

@Column(name = "tel_merc", nullable = true)
private String telefone;

@Column(name = "whatzap_merc", nullable = true)
private String whatsapp;

@Column(name = "email_merc", nullable = true)
private String email;

@Column(name = "ativo", nullable = true)
private Boolean ativo;

@Column(name = "logo_merc", nullable = true)
private String logo;

@OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@Column(name="id_catpro", insertable = true)
private List<Categoria> categorias;

public Integer getId() {
    return id;
}

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

public String getCnpj() {
    return cnpj;
}

public void setCnpj(String cnpj) {
    this.cnpj = cnpj;
}

public String getNomeFantasia() {
    return nomeFantasia;
}

public void setNomeFantasia(String nomeFantasia) {
    this.nomeFantasia = nomeFantasia;
}

public String getNome() {
    return nome;
}

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

public String getEnd() {
    return end;
}

public void setEnd(String end) {
    this.end = end;
}

public String getBairro() {
    return bairro;
}

public void setBairro(String bairro) {
    this.bairro = bairro;
}

public String getCep() {
    return cep;
}

public void setCep(String cep) {
    this.cep = cep;
}

public String getTelefone() {
    return telefone;
}

public void setTelefone(String telefone) {
    this.telefone = telefone;
}

public String getWhatsapp() {
    return whatsapp;
}

public void setWhatsapp(String whatsapp) {
    this.whatsapp = whatsapp;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public Boolean getAtivo() {
    return ativo;
}

public void setAtivo(Boolean ativo) {
    this.ativo = ativo;
}

public String getLogo() {
    return logo;
}

public void setLogo(String logo) {
    this.logo = logo;
}

public List<Categoria> getCategorias() {
    return categorias;
}

public void setCategorias(List<Categoria> categorias) {
    this.categorias = categorias;
}

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

}

Classe Categoria

package br.com.fractal.mercado.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;

@Entity
@Table(name = "categoria_prod")
public class Categoria implements Serializable {

    private static final long serialVersionUID = 8923549761906770242L;

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

    @Column(name = "descricao_catpro", nullable = true)
    private String descricao;

    @Column(name = "cnpj_merc")
    private String cnpj;

    public Integer getId() {
        return id;
    }

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

    public String getDescricao() {
        return descricao;
    }

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

    public String getCnpj() {
        return cnpj;
    }

    public void setCnpj(String cnpj) {
        this.cnpj = cnpj;
    }

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



}

Mercado DAO, o método é o inserir

package br.com.fractal.mercado.dao;

import java.util.ArrayList;
import java.util.List;

import org.jboss.logging.Logger;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import br.com.fractal.mercado.conexao.Conexao;
import br.com.fractal.mercado.entity.Mercado;

@RestController
@RequestMapping(consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Transactional(propagation=Propagation.REQUIRES_NEW)
public class MercadoDAO extends Conexao {

    private Logger LOGGER = Logger.getLogger(MercadoDAO.class);


    @GetMapping(value="consultarMercados", produces=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public List<Mercado> consultarMercados() {
        List<Mercado> mercados = new ArrayList<Mercado>();
        try {
            obterSession();
            mercados.addAll(sessao.createQuery("From Mercado").getResultList());
        }
        catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
        finally {
            fecharConexao();
        }
        return mercados;
    }


    @PostMapping(value = "inserirMercado")
    public void inserirMercado(@RequestBody Mercado mercado) {
        try {
            obterSession();
            sessao.getTransaction().begin();
            sessao.save(mercado);
        }
        catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
        finally {
            fecharConexao();
        }
    }

}

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software