[RESOLVIDO]Erro ao inserir dados no banco de dados, usando hibernate+SQL Server 2008

7 respostas
J

Olá!

Estou construindo uma aplicação desktop em Java. Utilizo a plataforma NetBeans, framework Hibernate e Banco de Dados SQL Server 2008. A minha aplicação se trata de um Sistema de Controle Bibliotecário. No banco de dados criei uma tabela Usuário para generalizar atributos para outras classes como aluno, funcioanrio e etc. Para trabalhar com herança usando Hibernate usa-se na classe pai que é usuário o @Inheritance(strategy= InheritanceType.JOINED) e na classe que herda atributos da classe pai usa-se o @PrimaryKeyJoinColumn(name=“CodUsuario”), sendo que existe outras atribuições que devem ser feitas, essas aí são as principais. Além disso deve-se fazer o extends da subclasse com a classe pai.

Fiz tudo isso, porém tá dando erro na hora de inserir no banco de dados. E diz que o erro é no código!
Anexei os códigos das classes Usuário e Funcionário (Estou usando usuário como pessoa) para ver o que eu fiz.

O erro que aparece quando tento testar uma inserção de dados é o seguinte:

<a>color=red</a>

AVISO: SQL Error: 207, SQLState: S0001

06/12/2011 13:55:54 org.hibernate.util.JDBCExceptionReporter logExceptions

GRAVE: Invalid column name ‘CodUsuario’.

06/12/2011 13:55:54 org.hibernate.event.def.AbstractFlushingEventListener performExecutions

GRAVE: Could not synchronize database state with session

org.hibernate.exception.SQLGrammarException: could not insert: [br.com.Dominio.Funcionario]

at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)

at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2267)

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2660)

at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:56)

at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)

at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:234)

at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)

at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)

at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)

at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)

at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)

at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)

at br.com.Persistencia.GenericHibernateDAO.salvar(GenericHibernateDAO.java:66)

at br.com.Testes.TesteConexao.main(TesteConexao.java:39)

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name ‘CodUsuario’.

at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)

at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1454)

at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:388)

at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:338)

at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026)

at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416)

at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:185)

at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:160)

at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:306)

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2250)

… 12 more

Exception in thread “main” org.hibernate.exception.SQLGrammarException: could not insert: [br.com.Dominio.Funcionario]

at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)

at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2267)

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2660)

at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:56)

at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)

at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:234)

at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)

at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)

at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)

at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)

at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)

at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)

at br.com.Persistencia.GenericHibernateDAO.salvar(GenericHibernateDAO.java:66)

at br.com.Testes.TesteConexao.main(TesteConexao.java:39)

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name ‘CodUsuario’.

at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)

at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1454)

at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:388)

at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:338)

at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026)

at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416)

at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:185)

at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:160)

at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:306)

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2250)

… 12 more

Java Result: 1[/color]

Alguém pode me ajudar!!!

7 Respostas

J

Vou anexar os códigos das classes DAO do Generic e do GenericHibernate, caso seja necessário.
:slight_smile:

Até.

R

Essa coluna CodUsuario existe na sua base exatamente como está escrito?

J

Olá, digaoneves!

Está anexo um PrintScreen dos atributos das classes Usuario e Funcionario do banco de dados que estou usando.



R

Tente alterar seu annotation deixando ele assim:

@PrimaryKeyJoinColumn(name="FK_Funcionario_Usuario")
J

Olá, digaoneves.

O erro ainda persiste. :cry:

Ps.: me dá detalhes desta ferramenta que você usou para colar o código. :smiley:

R

não é ferramenta nenhuma hehe..
são só os BBCode do fórum mesmo

digite seu código entre as BBCode
que ele ja formata pra voce

exemplo:

[code]
package bla

public class Classe{

}

poste assim e veja como fica

J

Olá!

Consegui inserir os dados no banco. O erro era no annotation da chave primaria na classe Funcionario. Veja o código:

@Entity
@PrimaryKeyJoinColumn(name="CodFuncionario")
@Table(name = "Funcionario", catalog = "dbControleBibliotecario", schema = "dbo")
public class Funcionario extends Usuario implements Serializable {
    
    private static final long serialVersionUID = 1L;
    
    @Basic(optional = false)
    @Column(name = "Cargo", nullable = false, length = 45)
    private String cargo;

    public Funcionario() {
    }

    public String getCargo() {
        return cargo;
    }

    public void setCargo(String cargo) {
        this.cargo = cargo;
    }

    @Override
    public String toString() {
        return "br.com.Dominio.Funcionario[ codFuncionario=" + getCodUsuario() + " ]";
    }

Como não defini que a classe Usuário seria abstract, então mantive o CodFuncionario como sendo chave primária. Sendo que no Override tem uma função que diz que o CodFuncionario = CodUsuario, por isso não teve bronca na hora de inserir. É isso mesmo??
O Código da classe Usuário é o seguinte:

@Entity
@Table(name = "Usuario", catalog = "dbControleBibliotecario", schema = "dbo")
@Inheritance(strategy= InheritanceType.JOINED)
public class Usuario implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "CodUsuario", nullable = false)
    private Integer codUsuario;
    @Basic(optional = false)
    @Column(name = "NomeUsuario", nullable = false, length = 255)
    private String nomeUsuario;
    @Basic(optional = false)
    @Column(name = "DataNascimento", nullable = false)
    @Temporal(TemporalType.DATE)
    private Date dataNascimento;
    @Basic(optional = false)
    @Column(name = "Sexo", nullable = false)
    private char sexo;
    @Basic(optional = false)
    @Column(name = "CPF", nullable = false, length = 15)
    private String cpf;
    @Basic(optional = false)
    @Column(name = "RG", nullable = false, length = 12)
    private String rg;
    @Basic(optional = false)
    @Column(name = "Logradouro", nullable = false, length = 255)
    private String logradouro;
    @Basic(optional = false)
    @Column(name = "Bairro", nullable = false, length = 45)
    private String bairro;
    @Basic(optional = false)
    @Column(name = "Cidade", nullable = false, length = 45)
    private String cidade;
    @Basic(optional = false)
    @Column(name = "Cep", nullable = false)
    private int cep;
    @Basic(optional = false)
    @Column(name = "UF", nullable = false, length = 2)
    private String uf;
    @Column(name = "Telefone", length = 13)
    private String telefone;
    @Basic(optional = false)
    @Column(name = "Celular", nullable = false, length = 13)
    private String celular;
    @Column(name = "Email", length = 45)
    private String email;
    @Column(name = "Observacao", length = 255)
    private String observacao;
    @Basic(optional = false)
    @Column(name = "DataCadastro", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date dataCadastro;
    @Basic(optional = false)
    @Column(name = "NuSenha", nullable = false, length = 6)
    private String nuSenha;

    public Usuario() {
    }

    public Usuario(Integer codUsuario) {
        this.codUsuario = codUsuario;
    }

    public Usuario(Integer codUsuario, String nomeUsuario, Date dataNascimento, char sexo, String cpf, String rg, String logradouro, String bairro, String cidade, int cep, String uf, String celular, Date dataCadastro, String nuSenha) {
        this.codUsuario = codUsuario;
        this.nomeUsuario = nomeUsuario;
        this.dataNascimento = dataNascimento;
        this.sexo = sexo;
        this.cpf = cpf;
        this.rg = rg;
        this.logradouro = logradouro;
        this.bairro = bairro;
        this.cidade = cidade;
        this.cep = cep;
        this.uf = uf;
        this.celular = celular;
        this.dataCadastro = dataCadastro;
        this.nuSenha = nuSenha;
    }

    public Integer getCodUsuario() {
        return codUsuario;
    }

    public void setCodUsuario(Integer codUsuario) {
        this.codUsuario = codUsuario;
    }

    public String getNomeUsuario() {
        return nomeUsuario;
    }

    public void setNomeUsuario(String nomeUsuario) {
        this.nomeUsuario = nomeUsuario;
    }

    public Date getDataNascimento() {
        return dataNascimento;
    }

    public void setDataNascimento(Date dataNascimento) {
        this.dataNascimento = dataNascimento;
    }

    public char getSexo() {
        return sexo;
    }

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

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getRg() {
        return rg;
    }

    public void setRg(String rg) {
        this.rg = rg;
    }

    public String getLogradouro() {
        return logradouro;
    }

    public void setLogradouro(String logradouro) {
        this.logradouro = logradouro;
    }

    public String getBairro() {
        return bairro;
    }

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

    public String getCidade() {
        return cidade;
    }

    public void setCidade(String cidade) {
        this.cidade = cidade;
    }

    public int getCep() {
        return cep;
    }

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

    public String getUf() {
        return uf;
    }

    public void setUf(String uf) {
        this.uf = uf;
    }

    public String getTelefone() {
        return telefone;
    }

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

    public String getCelular() {
        return celular;
    }

    public void setCelular(String celular) {
        this.celular = celular;
    }

    public String getEmail() {
        return email;
    }

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

    public String getObservacao() {
        return observacao;
    }

    public void setObservacao(String observacao) {
        this.observacao = observacao;
    }

    public Date getDataCadastro() {
        return dataCadastro;
    }

    public void setDataCadastro(Date dataCadastro) {
        this.dataCadastro = dataCadastro;
    }

    public String getNuSenha() {
        return nuSenha;
    }

    public void setNuSenha(String nuSenha) {
        this.nuSenha = nuSenha;
    }

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

    @Override
    public String toString() {
        return "br.com.Dominio.Usuario[ codUsuario=" + codUsuario + " ]";
    }

Até mais!! :D

Criado 6 de dezembro de 2011
Ultima resposta 7 de dez. de 2011
Respostas 7
Participantes 2