Problemas ao persistir

Ao realizar uma persistencia recebo a seguinte mensagemcom relação ao classe entity:

55 [http-8084-2] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 581 [http-8084-2] INFO org.hibernate.impl.SessionFactoryImpl - building session factory 903 [http-8084-2] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured 1221 [http-8084-2] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 42P01 1221 [http-8084-2] ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: relation "hibernate_sequence" does not exist Nao foi possivel Salvar o usuario :(could not get next sequence value :( 1223 [http-8084-2] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 25P02 1223 [http-8084-2] ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: current transaction is aborted, commands ignored until end of transaction block Nao foi possivel Salvar o usuariocould not get next sequence value

Algo refere a “could not get next sequence value”

Acredito que deve ser no @GeneratedValue que não esta conseguindo gerar o número serial conforme a minha classe entity. Alguem tem alguma sugestão?

Segue a Classe entity Usuario

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

package br.ifrr.entity;

import java.io.Serializable;
import javax.annotation.Generated;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 *
 * @author cristofe.rocha
 */
@Entity
@Table(name = "usuario")
@NamedQueries({
    @NamedQuery(name = "Usuario.findAll", query = "SELECT u FROM Usuario u"),
    @NamedQuery(name = "Usuario.findByAtivo", query = "SELECT u FROM Usuario u WHERE u.ativo = :ativo"),
    @NamedQuery(name = "Usuario.findByPermissao", query = "SELECT u FROM Usuario u WHERE u.permissao = :permissao"),
    @NamedQuery(name = "Usuario.findByPasswd", query = "SELECT u FROM Usuario u WHERE u.passwd = :passwd"),
    @NamedQuery(name = "Usuario.findByLogin", query = "SELECT u FROM Usuario u WHERE u.login = :login"),
    @NamedQuery(name = "Usuario.findByCodUsuario", query = "SELECT u FROM Usuario u WHERE u.codUsuario = :codUsuario"),
    @NamedQuery(name = "Usuario.findByNome", query = "SELECT u FROM Usuario u WHERE u.nome = :nome")})
public class Usuario implements Serializable {
    private static final long serialVersionUID = 1L;
    @Column(name = "ativo")
    private Integer ativo;
    @Column(name = "permissao")
    private Integer permissao;
    @Column(name = "passwd")
    private String passwd;
    @Column(name = "login")
    private String login;
    @Id
    @GeneratedValue
    @Column(name = "cod_usuario")
    private Integer codUsuario;
    @Column(name = "nome")
    private String nome;

    public Usuario() {
    }

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

    public Integer getAtivo() {
        return ativo;
    }

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

    public Integer getPermissao() {
        return permissao;
    }

    public void setPermissao(Integer permissao) {
        this.permissao = permissao;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public Integer getCodUsuario() {
        return codUsuario;
    }

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

    public String getNome() {
        return nome;
    }

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

    @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.ifrr.entity.Usuario[codUsuario=" + codUsuario + "]";
    }

}

A tabela do meu Banco :

[code]

Table: usuario

– DROP TABLE usuario;

CREATE TABLE usuario
(
ativo integer,
permissao integer,
passwd text,
“login” character varying,
cod_usuario bigserial NOT NULL,
nome character(1),
CONSTRAINT cod_usuario PRIMARY KEY (cod_usuario)
)
WITH (
OIDS=FALSE,
autovacuum_enabled=true
);
ALTER TABLE usuario OWNER TO postgres;
GRANT ALL ON TABLE usuario TO public;
GRANT ALL ON TABLE usuario TO postgres;
GRANT SELECT(“login”), UPDATE(“login”), INSERT(“login”), REFERENCES(“login”) ON usuario TO public;[/code]

Quando vc anotou o Id com GeneratedValue, o JPA deve estar procurando um sequence no BD, que não deve ter sido criada.

Vc pode criar uma sequence no BD (se este tiver suporte - mysql usa autoincremento) e mapeá-la na sua entidade, ou, passar o generatedValue alterando seu atributo generatedType para AUTO.

Se for mysql e decidir usar autoIncrement, em generatedType use IDENTITY

isso mesmo que o fabiomedeirosf falou.

se for postgres pode fazer assim…

@SequenceGenerator( name = "cod_seq", sequenceName = "cod_seq", allocationSize = 1 )
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="cod_seq")
@Column(name = "cod_usuario")  
private Integer codUsuario; 

O Banco é postgres, realizei as alterações conforme abaixo

 @Id
    @SequenceGenerator( name = "cod_seq", sequenceName = "cod_seq", allocationSize = 1 )
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="cod_seq")
    @Column(name = "cod_usuario")
    private Integer codUsuario;

Mas os Logs ainda continuam:

1366 [http-8084-1] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled 1367 [http-8084-1] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 1367 [http-8084-1] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 1397 [http-8084-1] INFO org.hibernate.impl.SessionFactoryImpl - building session factory 2143 [http-8084-1] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured 3604 [http-8084-1] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 42P01 3604 [http-8084-1] ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: relation "cod_seq" does not exist Nao foi possivel Salvar o usuariocould not get next sequence value 3743 [http-8084-1] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 25P02 3743 [http-8084-1] ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: current transaction is aborted, commands ignored until end of transaction block Nao foi possivel Salvar o usuario could not get next sequence value

Alguma outra sugestao? ou ainda tem alguma coisa errada?

Os logs mais completos

30 [http-8084-5] INFO org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.3.1.GA
308 [http-8084-5] INFO org.hibernate.cfg.Environment - Hibernate 3.2.5
330 [http-8084-5] INFO org.hibernate.cfg.Environment - hibernate.properties not found
342 [http-8084-5] INFO org.hibernate.cfg.Environment - Bytecode provider name : cglib
371 [http-8084-5] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
845 [http-8084-5] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
845 [http-8084-5] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
1281 [http-8084-5] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
2010 [http-8084-5] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.ifrr.entity.Usuario
2168 [http-8084-5] INFO org.hibernate.cfg.annotations.QueryBinder - Binding Named query: Usuario.findAll => SELECT u FROM Usuario u
2168 [http-8084-5] INFO org.hibernate.cfg.annotations.QueryBinder - Binding Named query: Usuario.findByAtivo => SELECT u FROM Usuario u WHERE u.ativo = :ativo
2168 [http-8084-5] INFO org.hibernate.cfg.annotations.QueryBinder - Binding Named query: Usuario.findByPermissao => SELECT u FROM Usuario u WHERE u.permissao = :permissao
2168 [http-8084-5] INFO org.hibernate.cfg.annotations.QueryBinder - Binding Named query: Usuario.findByPasswd => SELECT u FROM Usuario u WHERE u.passwd = :passwd
2168 [http-8084-5] INFO org.hibernate.cfg.annotations.QueryBinder - Binding Named query: Usuario.findByLogin => SELECT u FROM Usuario u WHERE u.login = :login
2168 [http-8084-5] INFO org.hibernate.cfg.annotations.QueryBinder - Binding Named query: Usuario.findByCodUsuario => SELECT u FROM Usuario u WHERE u.codUsuario = :codUsuario
2168 [http-8084-5] INFO org.hibernate.cfg.annotations.QueryBinder - Binding Named query: Usuario.findByNome => SELECT u FROM Usuario u WHERE u.nome = :nome
2679 [http-8084-5] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.ifrr.entity.Usuario on table usuario
2833 [http-8084-5] INFO org.hibernate.cfg.AnnotationConfiguration - Hibernate Validator not found: ignoring
3400 [http-8084-5] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
3400 [http-8084-5] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
3400 [http-8084-5] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
3442 [http-8084-5] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost:5432/aluno
3442 [http-8084-5] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=postgres, password=****}
5589 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - RDBMS: PostgreSQL, version: 9.0.3
5590 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 8.3 JDBC3 with SSL (build 603)
5642 [http-8084-5] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.PostgreSQLDialect
5648 [http-8084-5] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
5650 [http-8084-5] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
5650 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
5650 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
5650 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
5650 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
5651 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
5651 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): disabled
5651 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
5652 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
5652 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
5652 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
5652 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
5652 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
5654 [http-8084-5] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
5655 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
5655 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
5655 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
5655 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
5655 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Cache provider: org.hibernate.cache.NoCacheProvider
5655 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
5655 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
5659 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
5659 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
5660 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
5660 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
5754 [http-8084-5] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
7100 [http-8084-5] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
8950 [http-8084-5] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 42809
8950 [http-8084-5] ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: "cod_usuario" is not a sequence
Nao foi possivel Salvar o usuariocould not get next sequence value
8973 [http-8084-5] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 25P02
8973 [http-8084-5] ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: current transaction is aborted, commands ignored until end of transaction block
Nao foi possivel Salvar o usuariocould not get next sequence value

cria essa sequence na base e tenta dnovo…

CREATE SEQUENCE cod_seq
  INCREMENT 1 MINVALUE 1
  MAXVALUE 9223372036854775807 START 1
  CACHE 1;

Ele insere a linha ,mas retorna ainda um erro

85 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled 489 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled 489 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled 490 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 490 [http-8084-5] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 527 [http-8084-5] INFO org.hibernate.impl.SessionFactoryImpl - building session factory 1058 [http-8084-5] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured

Gera o insert com o cod_usuario preenchido de forma sequencial, ou seja deu certo, porém não insere os outros campos que são informados no formulário.

A tabela do banco foi criado assim:

[code]

  • Table: usuario

– DROP TABLE usuario;

CREATE TABLE usuario
(
ativo integer,
permissao integer,
passwd text,
“login” text,
cod_usuario serial NOT NULL,
nome character(10),
CONSTRAINT cod_usuario PRIMARY KEY (cod_usuario)
)
WITH (
OIDS=FALSE,
autovacuum_enabled=true
);
ALTER TABLE usuario OWNER TO postgres;
GRANT ALL ON TABLE usuario TO public;
GRANT ALL ON TABLE usuario TO postgres;
GRANT SELECT(“login”), UPDATE(“login”), INSERT(“login”), REFERENCES(“login”) ON usuario TO public;[/code]

Qual a versão do driver jdbc vc está usando?

Pegue a versão mais atual para o postgres.

Coloca o código onde tu chama a inserção. Já vi algo parecido quando se tenta gravar log de cada inserção em banco que se faz…