Could not execute JDBC batch update

Galera estou tentando fazer a primeira aplicação usando hibernate, sempre faço as querys e tudo mais na unha, mas resolvi aderir a este framework.

esta dando este erro ai acima vou colar o codigo aqui pra facilitar

aqui a classe de gravar. acho que é onde esta todo o erro. Estou utilizando POSTGRES

import javax.swing.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;

public class GravaAluno {

    public static void main(String[] args) {
        try {
            SessionFactory fabrica = new Configuration().configure().buildSessionFactory();
            Session sessao = fabrica.openSession();

            Aluno aluno = new Aluno();
            aluno.setAlu_codigo(1);
            aluno.setAlu_nome("Aluno da Silva coleção Set");
            aluno.setAlu_cidade("Sete");
            aluno.setAlu_fone("54 3330 1222");
            aluno.setAlu_curso("hibernate");
            Transaction tx_aluno = sessao.beginTransaction();
            sessao.save(aluno);
            tx_aluno.commit();
            sessao.close();
        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null, "Erro na insersão : " + erro);
        }
        //Hibernate: insert into alunos (alu_nome, alu_cidade, alu_fone, alu_curso, alu_codigo) values (?, ?, ?, ?, ?)


    }
}[/code]


AGORA MEU ARQUIVO Aluno.hbm.xml

[code]<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Paulo Manhani - Conectando com hibernate
    -->
<hibernate-mapping>
  <class name="Aluno" table="Alunos">
    <id column="alu_codigo" name="alu_codigo" type="int"/>
    <property name="alu_nome"/>
    <property name="alu_cidade"/>
    <property name="alu_fone"/>
    <property name="alu_curso"/>
  </class>
</hibernate-mapping>

e por ultimo o de configuração do hibernate

[code]<?xml version="1.0" encoding="UTF-8"?>

org.postgresql.Driver jdbc:postgresql://localhost/hibernate postgres mysenha org.hibernate.dialect.PostgreSQLDialect [/code]

cara,

poste o log de erro completo para o pessoal poder te ajudar.
Ja que vc está começando a estudar hibernate, pq vc não usa anotações muito mais facil de entender.

t+

run: 0 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.1.GA 16 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found 16 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist 16 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling 47 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml 47 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml 94 [main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : aluno.hbm.xml 156 [main] INFO org.hibernate.cfg.HbmBinder - Mapping class: Aluno -> Alunos 172 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null 203 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!) 203 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20 203 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false 219 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost/hibernate 219 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=postgres, password=****} 281 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: PostgreSQL, version: 9.1.1 281 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 9.0 JDBC4 (build 801) 281 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.PostgreSQLDialect 297 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions) 297 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 297 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15 297 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto 297 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1 297 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 297 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory 297 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {} 297 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory 297 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 297 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 328 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory 421 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured 468 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 42P01 468 [main] ERROR org.hibernate.util.JDBCExceptionReporter - Entrada em lote 0 insert into Alunos (alu_nome, alu_cidade, alu_fone, alu_curso, alu_codigo) values ('Aluno da Silva coleção Set', 'Sete', '54 3330 1222', 'hibernate', '1') foi abortada. Chame getNextException para ver a causa. 468 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 42P01 468 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ERRO: relação "alunos" não existe Posição: 13 468 [main] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137) at GravaAluno.main(GravaAluno.java:25) Caused by: java.sql.BatchUpdateException: Entrada em lote 0 insert into Alunos (alu_nome, alu_cidade, alu_fone, alu_curso, alu_codigo) values ('Aluno da Silva coleção Set', 'Sete', '54 3330 1222', 'hibernate', '1') foi abortada. Chame getNextException para ver a causa. at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2598) at org.postgresql.core.v3.QueryExecutorImpl$1.handleError(QueryExecutorImpl.java:459) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1836) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:407) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2737) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268) ... 8 more

ele ta acusando a linha do commit

cara,

vc tem certeza que a tabela Alunos existe, ve essa linha do seu erro

468 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ERRO: relação "alunos" não existe 

t+

Adiciona essa linha no seu arquivo de configurações:<property name="hibernate.hbm2ddl.auto">update</property>
Esse código irá criar/alterar os relacionamentos/tabelas do seu banco.

o erro continua olha o log, uma observação, ta dizendo na segunda linha ta dizendo que não encontrou hibernate.properties…eu não tenho mesmo este arquivo será isto?? alguém tem um modelo

0 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.1.GA 16 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found 16 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist 16 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling 47 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml 47 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml 109 [main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : aluno.hbm.xml 156 [main] INFO org.hibernate.cfg.HbmBinder - Mapping class: Aluno -> Alunos 172 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null 203 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!) 203 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20 203 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false 234 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost/hibernate 234 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=postgres, password=****} 281 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: PostgreSQL, version: 9.1.1 281 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 9.0 JDBC4 (build 801) 297 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.PostgreSQLDialect 297 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions) 297 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 297 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15 297 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto 297 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1 297 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 297 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory 297 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {} 297 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory 297 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled 297 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 297 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 328 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory 421 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured 421 [main] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - Running hbm2ddl schema update 421 [main] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - fetching database metadata 437 [main] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - updating schema 484 [main] INFO org.hibernate.tool.hbm2ddl.TableMetadata - table found: public.alunos 484 [main] INFO org.hibernate.tool.hbm2ddl.TableMetadata - columns: [alu_fone, alu_cidade, alu_codigo, alu_nome, alu_curso] 484 [main] INFO org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: [] 484 [main] INFO org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [alunos_pkey] 484 [main] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - schema update complete 546 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 23505 546 [main] ERROR org.hibernate.util.JDBCExceptionReporter - Entrada em lote 0 insert into Alunos (alu_nome, alu_cidade, alu_fone, alu_curso, alu_codigo) values ('Aluno da Silva coleção Set', 'Sete', '54 3330 1222', 'hibernate', '1') foi abortada. Chame getNextException para ver a causa. 546 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 23505 546 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ERRO: duplicar valor da chave viola a restrição de unicidade "alunos_pkey" Detalhe: Chave (alu_codigo)=(1) já existe. 546 [main] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137) at GravaAluno.main(GravaAluno.java:25) Caused by: java.sql.BatchUpdateException: Entrada em lote 0 insert into Alunos (alu_nome, alu_cidade, alu_fone, alu_curso, alu_codigo) values ('Aluno da Silva coleção Set', 'Sete', '54 3330 1222', 'hibernate', '1') foi abortada. Chame getNextException para ver a causa. at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2598) at org.postgresql.core.v3.QueryExecutorImpl$1.handleError(QueryExecutorImpl.java:459) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1836) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:407) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2737) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)

cara,

agora deu outro erro,

546 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ERRO: duplicar valor da chave viola a restrição de unicidade "alunos_pkey"  
  Detalhe: Chave (alu_codigo)=(1) já existe. 

falando que já existe essa chave, pq vc nao utiliza alguma forma de auto incremento.

t+

alisson agora vc me surprendeu, estou utilizando no banco o codigo como serial, ou seja autoincremento, a tabela esta vazia por total…rsrsrs no mato sem cachorro…vou rodar o scripit de criação da tabela pra ver novamente

este é o scripit da tabela, uma questao, la na tabela o codigo do aluno é auto incremento, em rotina normal via sql eu não preciso setar ele pra incluir, o banco preenche os campos que eu mandar e acrescenta o ID… como funciona aqui no hibernate?? se eu comento a linha de incluir código ele nao entra e com o codigo ele disse que ja existe…

outra coisa pelo que vi a sequencia de coluna nao esta certo no hibernate - columns: [alu_fone, alu_cidade, alu_codigo, alu_nome, alu_curso]

CREATE TABLE "Alunos" ( alu_codigo serial NOT NULL, alu_nome character varying(100), alu_cidade character varying(100), alu_fone character varying(100), alu_curso character varying(100), CONSTRAINT "PK_ALUNO" PRIMARY KEY (alu_codigo ) ) WITH ( OIDS=FALSE ); ALTER TABLE "Alunos" OWNER TO postgres;

cara,

no postgres não tem auto incremente, vc tem que criar uma sequence, segue um exemplo

CREATE SEQUENCE hibernate_sequence
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 2760
  CACHE 1;
ALTER TABLE hibernate_sequence OWNER TO postgres;

e qdo vc for setar as propriedades do seu objeto, o id tem que ser nulo.

t+

olha o que aconteceu, consegui gravar, só que eu fui no banco e tirei o auto incremento, passando a variavel de serial para integer…
ai simplesmente funcionou…só que como eu faço pra fazer isto funcionar com a variavel SERIAL de autoincremento

seu banco é postgres ou mysql?
nao tenho certeza mais acho que auto incremente funciona so com integer.

t+

[quote=manhanijava]olha o que aconteceu, consegui gravar, só que eu fui no banco e tirei o auto incremento, passando a variavel de serial para integer…
ai simplesmente funcionou…só que como eu faço pra fazer isto funcionar com a variavel SERIAL de autoincremento[/quote]

amigao o tipo de variavel SERIAL, no postgres é auto incremento

[quote=manhanijava][quote=manhanijava]olha o que aconteceu, consegui gravar, só que eu fui no banco e tirei o auto incremento, passando a variavel de serial para integer…
ai simplesmente funcionou…só que como eu faço pra fazer isto funcionar com a variavel SERIAL de autoincremento[/quote]

amigao o tipo de variavel SERIAL, no postgres é auto incremento[/quote]

não to conseguindo entender o por que de eu ter que setar a variavel alu_codigo.

por exemplo se eu fosse usar um sql eu não setaria o codigo somente as outras variaveis

eu não sabia que o tipo serial era auto incremente.

vc tem que seta-lo para null para o banco faz o incremente automatico.

da uma olhada neste link, ele pode te ajudar, http://stackoverflow.com/questions/2183932/hibernate-annotation-for-postgresql-serial-type

t+

[quote=alissonvla]eu não sabia que o tipo serial era auto incremente.

vc tem que seta-lo para null para o banco faz o incremente automatico.

da uma olhada neste link, ele pode te ajudar, http://stackoverflow.com/questions/2183932/hibernate-annotation-for-postgresql-serial-type

t+[/quote]

EU olhei o codigo, mas veja só, eu fui no banco de dados e setei o alu_codigo como null, mas assi que eu crio a primary key ele volta aser not null rsrs esta ta dificil…

mas valew muito obrigado pela atençao

rsrsrs
vc vai fazer isso no seu codigo, nao no banco, qdo tiver fazendo save.

t+

Se for o caso, faça como o alissonvla disse lá trás.

Crie uma Sequence, que seria melhor.

Aqui eu mostro como é feito: SequenceGenerator.