Novato em Hibernate [Resolvido]

4 respostas
billguedes

Estou me aventurando no mundo Java, já sei usar o Swing e JDBC.
Fiz uma tela de cadastro, inserção, alteração e pesquisa, utilizando os frameworks acima, e funcionou muito bem.
Resolvi dar mais um passo, implementar o framework Hibernate, procurei no google alguns tutorias e adaptei-los para minha necessidade e versão.
Infelizmente, não consigo fazer o Hibernate gravar no banco de dados, pensando que poderia ser problema no banco, troquei de Postgresql por Mysql, mas o erro continua o mesmo.
Novato como sou, não consigo achar o erro, onde estou errando?
Abaixo segue o código fonte para análise:

Cliente.sql

CREATE TABLE IF NOT EXISTS `cliente` ( `nome` varchar(30) default NULL, `id_cliente` int(11) NOT NULL auto_increment, PRIMARY KEY (`id_cliente`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

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.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibe</property> <property name="hibernate.connection.username">root</property> <mapping resource="hibe/Cliente.hbm.xml"/> </session-factory> </hibernate-configuration>

HibernateUtil.java

[code=java]/*

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

package hibe;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**

  • Hibernate Utility class with a convenient method to get Session Factory object.

  • @author billguedes
    
    */
    
    public class HibernateUtil {
    
    private static final SessionFactory sessionFactory;
    
    static {
    
    try {
    
    // Create the SessionFactory from standard (hibernate.cfg.xml)
    
    // config file.
    
    sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
    
    } catch (Throwable ex) {
    
    // Log the exception.
    
    System.err.println("Initial SessionFactory creation failed." + ex);
    
    throw new ExceptionInInitializerError(ex);
    
    }
    
    }
    
    public static SessionFactory getSessionFactory() {
    
    return sessionFactory;
    
    }
    
    }[/code]
    

Cliente.hbm.xml

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 06/06/2009 23:59:35 by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="hibe.Cliente" table="cliente" catalog="hibe"> <id name="idCliente" type="java.lang.Integer"> <column name="id_cliente" /> <generator class="identity" /> </id> <property name="nome" type="string"> <column name="nome" length="30" /> </property> </class> </hibernate-mapping>

Cliente.java

[code=java]package hibe;
// Generated 06/06/2009 23:59:34 by Hibernate Tools 3.2.1.GA

/**

  • Cliente generated by hbm2java
    */
    public class Cliente implements java.io.Serializable {

    private Integer idCliente;
    private String nome;

    public Cliente() {
    }

    public Cliente(String nome) {
    
    this.nome = nome;
    
    }
    
    public Integer getIdCliente() {
    
    return this.idCliente;
    
    }
    
    public void setIdCliente(Integer idCliente) {
    
    this.idCliente = idCliente;
    
    }
    
    public String getNome() {
    
    return this.nome;
    
    }
    
    public void setNome(String nome) {
    
    this.nome = nome;
    
    }
    
    }[/code]
    

Main.java

[code=java]package hibe;

import org.hibernate.Session;

public class Main {

public static void main(String[] args) {
    Cliente cliente= new Cliente();
    cliente.setNome("Terra NetWork");

    Session sessao= HibernateUtil.getSessionFactory().openSession();
    sessao.save(cliente);
    sessao.flush();
    sessao.close();
}

}

Log de saída

07/06/2009 06:12:30 org.hibernate.cfg.annotations.Version <clinit> INFO: Hibernate Annotations 3.3.1.GA 07/06/2009 06:12:30 org.hibernate.cfg.Environment <clinit> INFO: Hibernate 3.2.5 07/06/2009 06:12:30 org.hibernate.cfg.Environment <clinit> INFO: hibernate.properties not found 07/06/2009 06:12:30 org.hibernate.cfg.Environment buildBytecodeProvider INFO: Bytecode provider name : cglib 07/06/2009 06:12:30 org.hibernate.cfg.Environment <clinit> INFO: using JDK 1.4 java.sql.Timestamp handling 07/06/2009 06:12:30 org.hibernate.cfg.Configuration configure INFO: configuring from resource: /hibernate.cfg.xml 07/06/2009 06:12:30 org.hibernate.cfg.Configuration getConfigurationInputStream INFO: Configuration resource: /hibernate.cfg.xml 07/06/2009 06:12:31 org.hibernate.cfg.Configuration addResource INFO: Reading mappings from resource : hibe/Cliente.hbm.xml 07/06/2009 06:12:31 org.hibernate.cfg.Configuration doConfigure INFO: Configured SessionFactory: null 07/06/2009 06:12:31 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues INFO: Mapping class: hibe.Cliente -> cliente 07/06/2009 06:12:31 org.hibernate.cfg.AnnotationConfiguration secondPassCompile INFO: Hibernate Validator not found: ignoring 07/06/2009 06:12:32 org.hibernate.connection.DriverManagerConnectionProvider configure INFO: Using Hibernate built-in connection pool (not for production use!) 07/06/2009 06:12:32 org.hibernate.connection.DriverManagerConnectionProvider configure INFO: Hibernate connection pool size: 20 07/06/2009 06:12:32 org.hibernate.connection.DriverManagerConnectionProvider configure INFO: autocommit mode: false 07/06/2009 06:12:32 org.hibernate.connection.DriverManagerConnectionProvider configure INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/hibe 07/06/2009 06:12:32 org.hibernate.connection.DriverManagerConnectionProvider configure INFO: connection properties: {user=root} 07/06/2009 06:12:32 org.hibernate.cfg.SettingsFactory buildSettings INFO: RDBMS: MySQL, version: 5.0.51a-3ubuntu5.4 07/06/2009 06:12:32 org.hibernate.cfg.SettingsFactory buildSettings INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.6 ( Revision: ${svn.Revision} ) 07/06/2009 06:12:32 org.hibernate.dialect.Dialect <init> INFO: Using dialect: org.hibernate.dialect.MySQLDialect 07/06/2009 06:12:32 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory INFO: Using default transaction strategy (direct JDBC transactions) 07/06/2009 06:12:32 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 07/06/2009 06:12:32 org.hibernate.cfg.SettingsFactory buildSettings INFO: Automatic flush during beforeCompletion(): disabled 07/06/2009 06:12:32 org.hibernate.cfg.SettingsFactory buildSettings INFO: Automatic session close at end of transaction: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: JDBC batch size: 15 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: JDBC batch updates for versioned data: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Scrollable result sets: enabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: JDBC3 getGeneratedKeys(): enabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Connection release mode: auto 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Maximum outer join fetch depth: 2 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Default batch fetch size: 1 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Generate SQL with comments: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Order SQL updates by primary key: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Order SQL inserts for batching: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 07/06/2009 06:12:33 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init> INFO: Using ASTQueryTranslatorFactory 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Query language substitutions: {} 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: JPA-QL strict compliance: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Second-level cache: enabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Query cache: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory createCacheProvider INFO: Cache provider: org.hibernate.cache.NoCacheProvider 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Optimize cache for minimal puts: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Structured second-level cache entries: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Statistics: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Deleted entity synthetic identifier rollback: disabled 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Default entity-mode: pojo 07/06/2009 06:12:33 org.hibernate.cfg.SettingsFactory buildSettings INFO: Named query checking : enabled 07/06/2009 06:12:33 org.hibernate.impl.SessionFactoryImpl <init> INFO: building session factory 07/06/2009 06:12:33 org.hibernate.impl.SessionFactoryObjectFactory addInstance INFO: Not binding factory to JNDI, no JNDI name configured

Disposição
-Hibe
–pacote padrão
—hibernate.cfg.xml
–hibe
—Cliente.hbm.xml
—Cliente.java
—HibernateUtil.java
—Main.java
—hibernate.reveng.xml

4 Respostas

O

Brother, você achou uns tutoriais bem antigos hein? Ainda está mapeando suas entidades em xml. Hoje você já pode mapear na própria classe através de anotações. Dá uma olhada nesse screencast do Fabio Kung da Caelum: http://blog.caelum.com.br/2007/05/15/screencast-primeiros-passos-para-a-jpa

Não é novo, mas ainda é atual. Talvez você encontre algumas dificuldades entre a versão usada e a atual, mas qualquer dúvida, posta aí.

billguedes

Seguindo outro tutorial adicionei no LOG a apresentação do SQL, apresentando a mensagem:

R

Pode me chamar de velha-guarda, mas ainda prefiro fazer meus mapeamentos em XML :wink:

billguedes

Soluçao 1: Adiciona em hibernate.cfg.xml

Soluçao 2: Adiciona em Main.java

sessao.beginTransaction(); ... sessao.getTransaction().commit();

Criado 7 de junho de 2009
Ultima resposta 8 de jun. de 2009
Respostas 4
Participantes 3