[RESOLVIDO] Hibernate - Erro de inserção: Could Not execute JDBC batch Update

Estou com problemas para fazer o hibernate funcionar corretamente, é um teste com uma só tabela sem relacionamentos por enquanto… para depois prosseguir. Esto usando o MySql com PhpMyAdm.

Primeiro vou mostrar a minha tabela:

Tabela Alunos:

alu_cod int
alu_nome varchar
alu_curso varchar
alu_cidade varchar
alu_fone varchar

Agora minha classe POJO:

    private int alu_cod;
    private String alu_nome;
    private String alu_cidade;
    private String alu_fone;
    private String alu_curso;

Meu hibernate.cfg.xml :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">
            com.mysql.jdbc.Driver 
        </property>
        <property name="hibernate.connection.url">
           jdbc:mysql://localhost:3306/JAVA-HIBERNATE
        </property>
        <property name="hibernate.connection.username">
          root
        </property>
        <property name="hibernate.connection.password">
            311283
        </property>
        <property name="hibernate.dialect">
           org.hibernate.dialect.MySQLDialect
        </property>
 
        
        <property name="pool_size">10</property>

        <mapping resource="aluno.hbm.xml"/>
       

    </session-factory>
</hibernate-configuration>

O arquivo resource de mapeamento aluno.hbm.xml :
(Acredito que o erro está aqui!!! Não coloquei o column nos campos pois são memso nome, nem o type pelo mesmo motivo )

<?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">
<hibernate-mapping>
  <class name="Aluno" table="alunos">
    <id name="alu_cod" column="alu_cod" type="int"/>
    <properties name="alu_nome" />
    <properties name="alu_cidade" />
    <properties name="alu_fone" />
    <properties name="alu_curso" />
  </class>
</hibernate-mapping>

Aqui a classe de teste:

     SessionFactory fabricaSessoes = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
     Session sessao = fabricaSessoes.openSession();

     Aluno aluno = new Aluno();
     aluno.setAlu_cod(1);
     aluno.setAlu_nome("EDUARDO");
     aluno.setAlu_fone("88380438");
     aluno.setAlu_cidade("Joao Pessoa");
     aluno.setAlu_curso("Sistemas de Informações");

     Transaction tx_aluno = sessao.beginTransaction();
     sessao.save(aluno);
     tx_aluno.commit();
     sessao.close();
    

     }catch(Exception erro){
       JOptionPane.showMessageDialog(null, "Erro de inserção: "+erro);
     }

Aqui o erro:

2 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
32 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
32 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
94 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: hibernate.cfg.xml
94 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: hibernate.cfg.xml
219 [main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : aluno.hbm.xml
422 [main] INFO org.hibernate.cfg.HbmBinder - Mapping class: Aluno -> alunos
454 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
579 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
579 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
579 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
594 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/JAVA-HIBERNATE
594 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root, password=****}
860 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.0.51a-community-nt
860 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.0.8 ( Revision: ${svn.Revision} )
891 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect
891 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
907 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
907 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
907 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
907 [main] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
907 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
907 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
907 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
907 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
907 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
907 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
907 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
922 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
922 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
922 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
922 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
985 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
1235 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
1344 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1364, SQLState: HY000
1344 [main] ERROR org.hibernate.util.JDBCExceptionReporter - Field 'alu_nome' doesn't have a default value
1344 [main] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
        at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126)
        at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114)
        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)
       [color=red][b] at GravaAluno.main(GravaAluno.java:31)[/b][/color]
Caused by: java.sql.BatchUpdateException: Field 'alu_nome' doesn't have a default value
        at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1269)
        at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:955)
        at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
        ... 8 more

A linha do erro é qnd uso o comit();

Acredito que o erro está no arquivo aluno.hbm.xml , no mapeamento dos tipos e colunas…

O erro que sai da classe de aplicação é po seguinte:

Erro de inserção: org.hibernate.exception.GenericJBDCException : Could Not execute JDBC batch Update

MEUS IRMAOS ME AJUDEM AÍ PQ JÁ TÔ ATRASADAO NO ESTUDO , ESTE É O TERCEIRO BANCO QUE USO… QUAL O PROBLEMA ESTA ACONTECENDO?

<?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">
<hibernate-mapping>
  <class name="Aluno" table="alunos">
    <id name="alu_cod" column="alu_cod" type="int">      
      <generator class="native"/>
    </id>
    <property name="alu_nome" />
    <property name="alu_cidade" />
    <property name="alu_fone" />
    <property name="alu_curso" />
  </class>
</hibernate-mapping> 

Tenta assim.

Testei dessa forma mas ocorre este erro:
[b] org.hibernate.exception.GenericJBDCException : Could Not insert [Aluno]

O erro:

16 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.1.GA 32 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found 32 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist 32 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling 94 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: hibernate.cfg.xml 94 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: hibernate.cfg.xml 203 [main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : aluno.hbm.xml 407 [main] INFO org.hibernate.cfg.HbmBinder - Mapping class: Aluno -> alunos 422 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null 516 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!) 516 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20 516 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false 532 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/JAVA-HIBERNATE 532 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root, password=****} 797 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.0.51a-community-nt 797 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.0.8 ( Revision: ${svn.Revision} ) 813 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect 828 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions) 828 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 828 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled 828 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled 828 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15 828 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled 828 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled 828 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled 828 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto 828 [main] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2 828 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1 828 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled 828 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled 828 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled 828 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 844 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory 844 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {} 844 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled 844 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled 844 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled 844 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory 844 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled 844 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled 844 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled 844 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled 844 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 844 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 907 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory 1141 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured 1235 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1364, SQLState: HY000 1235 [main] ERROR org.hibernate.util.JDBCExceptionReporter - Field 'alu_cod' doesn't have a default value

Acho q o problema então está no seu banco de dados.

Manda o script usado para criar a tabela alunos.

Testei aqui exatamente como vc postou, apenas com as modificações que eu sugeri e não deu Erro.

A propósito, no seu arquivo hibernate.cfg.xml, inclua essas linhas:

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property> 

Amigão , funcionou aqui , consegui persistir, o problema era na tag <properties> que vc colocou <property> e eu não reparei , só reparei o “generate” que incluisse, colocando a tag corretinha funcionou legal… Proximo passo é estudar mais um pouco o feijão com arroz e passar para anotations.

Valeu!! :smiley: