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

3 respostas
E

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?

3 Respostas

G

hibernate.properties
cara acho q ta dando erro na propriedade do seu hibernate pq ele ta mapeando a classe aluno
e tenta usar JPA vai tirar esse xml do seu programa

E

Qual propiedade amigo?

<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>
P

Caused by: java.sql.BatchUpdateException: Field 'alu_nome' doesn't have a default value

O erro é este.

tenta deixar seu mapeamento assim:
<?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>
    <properties name="alu_nome" column="alu_nome" type="string"/>  
    <properties name="alu_cidade" column="alu_cidade" type="string"/>  
    <properties name="alu_fone" column="alu_fone" type="string"/>  
    <properties name="alu_curso" column="alu_curso" type="string"/>  
  </class>  
</hibernate-mapping>

Tenta colocar sempre qual coluna este atributo esta referenciando e qual o tipo.

Criado 18 de agosto de 2010
Ultima resposta 19 de ago. de 2010
Respostas 3
Participantes 3