Problema mapemento Hibernate

4 respostas
viniciusfaleiro

Galera…
As classes são geradas automáticamente com a ferramente do NetBeans

Qdo inicio minha aplicação eu recebo esse erro: (JSF + RICHFACES + HIBERNATE + GlassFish v2.2)

org.hibernate.AnnotationException: referencedColumnNames(ID) of MngBeans.Funcionario.setorId referencing MngBeans.Setor not mapped to a single property

Nunca vi esse problema… o que poderia ser?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MngBeans;

import DAOs.FuncionarioDAO;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.Session;

/**
 *
 * @author Vinicius
 */
@Entity
@Table(name = "funcionario")
@NamedQueries({
    @NamedQuery(name = "Funcionario.findAll", query = "SELECT f FROM Funcionario f"),
    @NamedQuery(name = "Funcionario.findByRg", query = "SELECT f FROM Funcionario f WHERE f.funcionarioPK.rg = :rg"),
    @NamedQuery(name = "Funcionario.findByEmpresaId", query = "SELECT f FROM Funcionario f WHERE f.funcionarioPK.empresaId = :empresaId"),
    @NamedQuery(name = "Funcionario.findByDtNascimento", query = "SELECT f FROM Funcionario f WHERE f.dtNascimento = :dtNascimento"),
    @NamedQuery(name = "Funcionario.findByEmail", query = "SELECT f FROM Funcionario f WHERE f.email = :email")})
public class Funcionario implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected FuncionarioPK funcionarioPK;
    @Lob
    @Column(name = "NOME")
    private String nome;
    @Column(name = "DT_NASCIMENTO")
    @Temporal(TemporalType.DATE)
    private Date dtNascimento;
    @Column(name = "EMAIL")
    private String email;
    @JoinTable(name = "resp_setor", joinColumns = {
        @JoinColumn(name = "FUNCIONARIO_RG", referencedColumnName = "RG"),
        @JoinColumn(name = "FUNCIONARIO_EMPRESA_ID", referencedColumnName = "EMPRESA_ID")}, inverseJoinColumns = {
        @JoinColumn(name = "SETOR_ID", referencedColumnName = "ID")})
    @ManyToMany
    private Collection<Setor> setorCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "funcionario")
    private Collection<CentroCusto> centroCustoCollection;
    @JoinColumns({
        @JoinColumn(name = "CENTRO_CUSTO_COD", referencedColumnName = "COD"),
        @JoinColumn(name = "CENTRO_CUSTO_EMPRESA_ID", referencedColumnName = "EMPRESA_ID")})
    @ManyToOne(optional = false)
    private CentroCusto centroCusto;
    @JoinColumn(name = "SEXO", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Sexo sexo;
    @JoinColumn(name = "ATIVO", referencedColumnName = "id")
    @ManyToOne
    private Status ativo;
    @JoinColumn(name = "SETOR_ID", referencedColumnName = "ID")
    @ManyToOne
    private Setor setorId;
    @JoinColumn(name = "EMPRESA_ID", referencedColumnName = "ID", insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private Empresa empresa;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "funcionario")
    private Collection<ParticipanteAula> participanteAulaCollection;

    public Funcionario() {
    }

    public Funcionario(FuncionarioPK funcionarioPK) {
        this.funcionarioPK = funcionarioPK;
    }

    public Funcionario(int rg, int empresaId) {
        this.funcionarioPK = new FuncionarioPK(rg, empresaId);
    }

    public FuncionarioPK getFuncionarioPK() {
        return funcionarioPK;
    }

    public void setFuncionarioPK(FuncionarioPK funcionarioPK) {
        this.funcionarioPK = funcionarioPK;
    }

    public String getNome() {
        return nome;
    }

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

    public Date getDtNascimento() {
        return dtNascimento;
    }

    public void setDtNascimento(Date dtNascimento) {
        this.dtNascimento = dtNascimento;
    }

    public String getEmail() {
        return email;
    }

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

    public Collection<Setor> getSetorCollection() {
        return setorCollection;
    }

    public void setSetorCollection(Collection<Setor> setorCollection) {
        this.setorCollection = setorCollection;
    }

    public Collection<CentroCusto> getCentroCustoCollection() {
        return centroCustoCollection;
    }

    public void setCentroCustoCollection(Collection<CentroCusto> centroCustoCollection) {
        this.centroCustoCollection = centroCustoCollection;
    }

    public CentroCusto getCentroCusto() {
        return centroCusto;
    }

    public void setCentroCusto(CentroCusto centroCusto) {
        this.centroCusto = centroCusto;
    }

    public Sexo getSexo() {
        return sexo;
    }

    public void setSexo(Sexo sexo) {
        this.sexo = sexo;
    }

    public Status getAtivo() {
        return ativo;
    }

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

    public Setor getSetorId() {
        return setorId;
    }

    public void setSetorId(Setor setorId) {
        this.setorId = setorId;
    }

    public Empresa getEmpresa() {
        return empresa;
    }

    public void setEmpresa(Empresa empresa) {
        this.empresa = empresa;
    }

    public Collection<ParticipanteAula> getParticipanteAulaCollection() {
        return participanteAulaCollection;
    }

    public void setParticipanteAulaCollection(Collection<ParticipanteAula> participanteAulaCollection) {
        this.participanteAulaCollection = participanteAulaCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (funcionarioPK != null ? funcionarioPK.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 Funcionario)) {
            return false;
        }
        Funcionario other = (Funcionario) object;
        if ((this.funcionarioPK == null && other.funcionarioPK != null) || (this.funcionarioPK != null && !this.funcionarioPK.equals(other.funcionarioPK))) {
            return false;
        }
        return true;
    }

    public String logar() {
        Session session = Util.HibernateUtil.getSessionFactory().openSession();
        FuncionarioDAO acessoDAO = new FuncionarioDAO(session);

        return acessoDAO.verificaAutenticacao(this);
    }

    @Override
    public String toString() {
        return "MngBeans.Funcionario[funcionarioPK=" + funcionarioPK + "]";
    }

}

Setor

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MngBeans;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 *
 * @author Vinicius
 */
@Entity
@Table(name = "setor")
@NamedQueries({
    @NamedQuery(name = "Setor.findAll", query = "SELECT s FROM Setor s"),
    @NamedQuery(name = "Setor.findById", query = "SELECT s FROM Setor s WHERE s.setorPK.id = :id"),
    @NamedQuery(name = "Setor.findByEmpresaId", query = "SELECT s FROM Setor s WHERE s.setorPK.empresaId = :empresaId")})
public class Setor implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected SetorPK setorPK;
    @Lob
    @Column(name = "DESCRICAO")
    private String descricao;
    @ManyToMany(mappedBy = "setorCollection")
    private Collection<Funcionario> funcionarioCollection;
    @JoinColumn(name = "EMPRESA_ID", referencedColumnName = "ID", insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private Empresa empresa;
    @OneToMany(mappedBy = "setorId")
    private Collection<Funcionario> funcionarioCollection1;
    @OneToMany(mappedBy = "setorId")
    private Collection<Planejamento> planejamentoCollection;

    public Setor() {
    }

    public Setor(SetorPK setorPK) {
        this.setorPK = setorPK;
    }

    public Setor(int id, int empresaId) {
        this.setorPK = new SetorPK(id, empresaId);
    }

    public SetorPK getSetorPK() {
        return setorPK;
    }

    public void setSetorPK(SetorPK setorPK) {
        this.setorPK = setorPK;
    }

    public String getDescricao() {
        return descricao;
    }

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

    public Collection<Funcionario> getFuncionarioCollection() {
        return funcionarioCollection;
    }

    public void setFuncionarioCollection(Collection<Funcionario> funcionarioCollection) {
        this.funcionarioCollection = funcionarioCollection;
    }

    public Empresa getEmpresa() {
        return empresa;
    }

    public void setEmpresa(Empresa empresa) {
        this.empresa = empresa;
    }

    public Collection<Funcionario> getFuncionarioCollection1() {
        return funcionarioCollection1;
    }

    public void setFuncionarioCollection1(Collection<Funcionario> funcionarioCollection1) {
        this.funcionarioCollection1 = funcionarioCollection1;
    }

    public Collection<Planejamento> getPlanejamentoCollection() {
        return planejamentoCollection;
    }

    public void setPlanejamentoCollection(Collection<Planejamento> planejamentoCollection) {
        this.planejamentoCollection = planejamentoCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (setorPK != null ? setorPK.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 Setor)) {
            return false;
        }
        Setor other = (Setor) object;
        if ((this.setorPK == null && other.setorPK != null) || (this.setorPK != null && !this.setorPK.equals(other.setorPK))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "MngBeans.Setor[setorPK=" + setorPK + "]";
    }

}

SetorPK

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MngBeans;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;

/**
 *
 * @author Vinicius
 */
@Embeddable
public class SetorPK implements Serializable {
    @Basic(optional = false)
    @Column(name = "ID")
    private int id;
    @Basic(optional = false)
    @Column(name = "EMPRESA_ID")
    private int empresaId;

    public SetorPK() {
    }

    public SetorPK(int id, int empresaId) {
        this.id = id;
        this.empresaId = empresaId;
    }

    public int getId() {
        return id;
    }

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

    public int getEmpresaId() {
        return empresaId;
    }

    public void setEmpresaId(int empresaId) {
        this.empresaId = empresaId;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (int) id;
        hash += (int) empresaId;
        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 SetorPK)) {
            return false;
        }
        SetorPK other = (SetorPK) object;
        if (this.id != other.id) {
            return false;
        }
        if (this.empresaId != other.empresaId) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "MngBeans.SetorPK[id=" + id + ", empresaId=" + empresaId + "]";
    }

}

4 Respostas

Requena

ficou meio confuso mas…
pelo erro e pelos beans, acretido que a coluna ‘ID’ referenciada no ‘SETOR_ID’ esta tentando referenciar setorId ao ID do Setor, e Setor não tem ID setor tem setorPK como chave quem tem ID é o setorPK, ai ele ta dando pau pq n achou o ID no bean Setor, provavelmente ele tentou dar um setor.getId() e nao conseguiu.

sei la, tenta colocar um ID no Setor ou entao tenta referenciar setorPk.ID em vez de ID direto no funcionario.

eu acho nao tenho certeza e não da para mim testar agora…

esse codigo foi meso gerado automaticamente? houve alterações?

viniciusfaleiro

Sim… fui tudo automático… já tinha o banco todo criado e apenas selecionei todas as tabelas e gerei… Eu tinha pensado nisso que vc falou agora… más não sei como ficaria na implementação…

Ficaria mto grato com sua ajuda…

No caso ai é simples… funcionário referencia Setor… setor tem uma chave primária composta… dai ta dando esse pau… O netbeans gera pra todos que tem chave composta um entidade.PK com as chaves…

Requena

Humm…
então tipo… chave composta em hibernate é um saco… pelo menos no meu ponto de vista… voce tentou algum outro tipo de mapeamento? tipo em vez de referenciar o ID referenciar setorPK.ID??? ou algo do tipo?

trabalho pouco com annotations então nao sei muito bém como fazer posso ter alguns palpites :D…

faz alguns testes ai… depois cola resultados pra gente conseguir dar uma resposta coerente…

viniciusfaleiro

Cara… não feliz eu fui analisar meu banco… ai percebi que minha FK estava apenas com id do setor… Lá no banco mesmo alterei pra id e empresa… dai ele gerou essa anotação:

@JoinColumns({
        @JoinColumn(name = "SETOR_ID", referencedColumnName = "ID"),
        @JoinColumn(name = "EMPRESA_ID", referencedColumnName = "EMPRESA_ID")})
    @ManyToOne(optional = false)
    private Setor setor;

To fazendo uns testes más acho que era isso…

Criado 21 de fevereiro de 2010
Ultima resposta 22 de fev. de 2010
Respostas 4
Participantes 2