Problemas com o Hibernate

8 respostas
pauloperes

Olá Pessoal

Estou tentando aprender a trabalhar com o Hibernate, consegui fazer tupo, o mapeamento, gerar a tabela na base de dados, porém quando mando rodar o programa, ele da um erro dizendo q o dialect não está setado, obs.: estou usando o Netbeans 4.1, Hibernate3 e como banco o PostgreSQL.

Ai vai os códigos:

/*
 * Produto.java
 *
 * Created on 18 de Maio de 2005, 15:34
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

/**
 *
 * @author Usuario
 */

    /**
     * Classe Modelo para um produto
     * @hibernate.class table="produto"
     */
public class Produto {
    private Long id;
    private String nome;
    private String descricao;
    private Double preco;
    
    public void setId(Long id){
        this.id = id;
    }
    
    /**
     * @hibernate.id generator-class="native"
     */
    public Long getId(){
        return this.id;
    }
    
    public void setNome(String nome){
        this.nome = nome;
    }
    
    /**
     * @hibernate.property not-null="true"
     */
    public String getNome(){
        return this.nome;
    }
    
    public void setDescricao(String descricao){
        this.descricao = descricao;
    }
    
    /**
     * @hibernate.property
     */
    public String getDescricao(){
        return this.descricao;
    }
    
    public void setPreco (Double preco){
        this.preco = preco;
    }
    
    /**
     * @hibernate.property
     */
    public Double getPreco(){
        return this.preco;
    }
}

Produto.hbm.xml

<?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="Produto"
        table="produto"
    >

        <id
            name="id"
            column="id"
            type="java.lang.Long"
        >
            <generator class="native">
              <!--  
                  To add non XDoclet generator parameters, create a file named 
                  hibernate-generator-params-Produto.xml 
                  containing the additional parameters and place it in your merge dir. 
              --> 
            </generator>
        </id>

        <property
            name="nome"
            type="java.lang.String"
            update="true"
            insert="true"
            column="nome"
            not-null="true"
        />

        <property
            name="descricao"
            type="java.lang.String"
            update="true"
            insert="true"
            column="descricao"
        />

        <property
            name="preco"
            type="java.lang.Double"
            update="true"
            insert="true"
            column="preco"
        />

        <!--
            To add non XDoclet property mappings, create a file named
                hibernate-properties-Produto.xml
            containing the additional properties and place it in your merge dir.
        -->

    </class>

</hibernate-mapping>

Hibernate.Properties

hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost/lagg1
hibernate.connection.username = postgres
hibernate.connection.password = kamikaze
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

Main.java

import org.hibernate.MappingException;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;


public class Main {
    public static void main(String args[]){
        try{
            Configuration cfg = new Configuration().addClass(Produto.class);
            SessionFactory factory = cfg.buildSessionFactory();
            factory.close();
        } catch (org.hibernate.HibernateException e){
            e.printStackTrace();
            e.getMessage();
        }
    }

}

e o erro que o compiler encontra

run:
(cfg.Environment                     460 ) Hibernate 3.0
(cfg.Environment                     473 ) hibernate.properties not found
(cfg.Environment                     506 ) using CGLIB reflection optimizer
(cfg.Environment                     536 ) using JDK 1.4 java.sql.Timestamp handling
(cfg.Configuration                   460 ) Mapping resource: Produto.hbm.xml
(cfg.HbmBinder                       258 ) Mapping class: Produto -> produto
(cfg.Configuration                   851 ) processing extends queue
(cfg.Configuration                   855 ) processing collection mappings
(cfg.Configuration                   864 ) processing association property references
(cfg.Configuration                   893 ) processing foreign key constraints
org.hibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect.
        at org.hibernate.dialect.Dialect.getDialect(Dialect.java:477)
        at org.hibernate.dialect.Dialect.getDialect(Dialect.java:499)
        at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:51)
        at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1505)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1053)
        at Main.main(Main.java:28)
BUILD SUCCESSFUL (total time: 1 second)

Se alguém puder me ajudar.

T+
Paulo

8 Respostas

danicuki

repare na seguinte mensagem:
(cfg.Environment 473 ) hibernate.properties not found

provavelmente o seu hibernate.properties não está no diretório raiz ou no diretório no qual o hibernate procura.

Eu costumo usar o hibenate.cfg.xml (funciona do mesmo jeito que o .properties)
e coloco sempre este arquivo no diretório raíz do projeto.

[]s

Daniel

pauloperes

Daniel,

Kra ja percebi esta mensagem, porém tenho ele na raiz, outra coisa q achei interessante, é que tenho um arquivo build.xml que gera a base de dados e o arquivo hbm.xml, quando mandei rodar ele, ele também falou que não encontrou o properties, porém crioui a tabela foi criada na base de dados, ou seja, o foi feito uma conexão.

tem como vc dar um exemplo desse hibernate.cfg.xml

Valeu

Paulo

wandersonxs

ta na mão

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

<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration.                   -->
<hibernate-configuration>

    <session-factory>
        <!-- properties -->
        <property name="connection.username">root</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
        <property name="connection.password"></property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

        <!-- mapping files -->
        <mapping resource="testes/Categoria.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

e para acessá-lo:

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html}.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * NOTICE: Location should be on the classpath as Hibernate uses
     * #resourceAsStream style lookup for its configuration file. That
     * is place the config file in a Java package - the default location
     * is the default Java package.<br><br>
     * Examples: <br>
     * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml". 
     * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code> 
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

    /** Holds a single instance of Session */
    private static final ThreadLocal threadLocal = new ThreadLocal();

    /** The single instance of hibernate configuration */
    private static final Configuration cfg = new Configuration();

    /** The single instance of hibernate SessionFactory */
    private static net.sf.hibernate.SessionFactory sessionFactory;

    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session currentSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

        if (session == null) {
            if (sessionFactory == null) {
                try {
                    cfg.configure(CONFIG_FILE_LOCATION);
                    sessionFactory = cfg.buildSessionFactory();
                }
                catch (Exception e) {
                    System.err.println("%%%% Error Creating SessionFactory %%%%");
                    e.printStackTrace();
                }
            }
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }

        return session;
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     * Default constructor.
     */
    private HibernateSessionFactory() {
    }

}

Repare q é diferente a forma de acesso do hibernate.cfg.xml do hibernate.properties.
Depois de algumas horas e dores de cabeça percebi isto. :x

Abraços
Wanderson :stuck_out_tongue:

pauloperes

Bom galera, ja resolvi aquele problema, agora estou com outro, vejam o erro:

init:
deps-jar:
compile:
run:
(cfg.Environment                     460 ) Hibernate 3.0
(cfg.Environment                     478 ) loaded properties from resource hibernate.properties: {hibernate.c3p0.timeout=1800, hibernate.connection.driver_class=org.postgresql.Driver, hibernate.cglib.use_reflection_optimizer=true, hibernate.c3p0.max_statements=50, hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect, hibernate.c3p0.max_size=20, hibernate.c3p0.min_size=5, hibernate.connection.username=postgres, hibernate.connection.url=jdbc:postgresql://localhost/lagg1, hibernate.connection.password=****}
(cfg.Environment                     506 ) using CGLIB reflection optimizer
(cfg.Environment                     536 ) using JDK 1.4 java.sql.Timestamp handling
(cfg.Configuration                   460 ) Mapping resource: Produto.hbm.xml
(cfg.HbmBinder                       258 ) Mapping class: Produto -> produto
(cfg.Configuration                   851 ) processing extends queue
(cfg.Configuration                   855 ) processing collection mappings
(cfg.Configuration                   864 ) processing association property references
(cfg.Configuration                   893 ) processing foreign key constraints
(dialect.Dialect                     91  ) Using dialect: org.hibernate.dialect.PostgreSQLDialect
(cfg.SettingsFactory                 90  ) Default batch fetch size: 1
(cfg.SettingsFactory                 94  ) Generate SQL with comments: disabled
(cfg.SettingsFactory                 98  ) Order SQL updates by primary key: disabled
(cfg.SettingsFactory                 273 ) Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
(ast.ASTQueryTranslatorFactory       21  ) Using ASTQueryTranslatorFactory
(cfg.SettingsFactory                 106 ) Query language substitutions: {}
(connection.C3P0ConnectionProvider   50  ) C3P0 using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost/lagg1
(connection.C3P0ConnectionProvider   51  ) Connection properties: {user=postgres, password=****}
(connection.C3P0ConnectionProvider   54  ) autocommit mode: false
(c3p0.C3P0Registry                   77  ) Initializing c3p0-0.9.0-pre6 [built 10-May-2005 20:32:30 -0400; debug? true; trace: 10]
(c3p0.PoolBackedDataSource           257 ) Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@13f3045 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@1efb836 [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1efb836, idleConnectionTestPeriod -> 0, initialPoolSize -> 5, maxIdleTime -> 1800, maxPoolSize -> 20, maxStatements -> 50, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@1c6f579 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 1c6f579, jdbcUrl -> jdbc:postgresql://localhost/lagg1, properties -> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 300, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, usesTraditionalReflectiveProxies -> false ], factoryClassLocation -> null, identityToken -> 13f3045, numHelperThreads -> 3 ]
(cfg.SettingsFactory                 148 ) JDBC batch size: 15
(cfg.SettingsFactory                 151 ) JDBC batch updates for versioned data: disabled
(cfg.SettingsFactory                 156 ) Scrollable result sets: enabled
(cfg.SettingsFactory                 164 ) JDBC3 getGeneratedKeys(): disabled
(transaction.TransactionFactoryFactory 31  ) Using default transaction strategy (direct JDBC transactions)
(transaction.TransactionManagerLookupFactory 33  ) No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
(cfg.SettingsFactory                 176 ) Automatic flush during beforeCompletion(): disabled
(cfg.SettingsFactory                 179 ) Automatic session close at end of transaction: disabled
(cfg.SettingsFactory                 260 ) Cache provider: org.hibernate.cache.EhCacheProvider
(cfg.SettingsFactory                 187 ) Second-level cache: enabled
(cfg.SettingsFactory                 192 ) Optimize cache for minimal puts: disabled
(cfg.SettingsFactory                 199 ) Structured second-level cache entries: enabled
(cfg.SettingsFactory                 203 ) Query cache: disabled
(cfg.SettingsFactory                 214 ) Statistics: disabled
(cfg.SettingsFactory                 218 ) Deleted entity synthetic identifier rollback: disabled
(cfg.SettingsFactory                 232 ) Default entity-mode: pojo
(impl.SessionFactoryImpl             140 ) building session factory
(config.Configurator                 126 ) No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/D:/Faculdade/Hibernate/lib/ehcache-1.1.jar!/ehcache-failsafe.xml
Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:164)
        at org.hibernate.id.IdentifierGeneratorFactory.class$(IdentifierGeneratorFactory.java:25)
        at org.hibernate.id.IdentifierGeneratorFactory.<clinit>(IdentifierGeneratorFactory.java:71)
        at org.hibernate.mapping.SimpleValue.createIdentifierGenerator(SimpleValue.java:135)
        at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:166)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1054)
        at Main.main(Main.java:29)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)

Sei q ta pedindo uma biblioteca, onde encontro ela, obs.: estou com a java 5

Valeu

Paulo

pauloperes

Galera,

Resovi, era aó as bibliotecas, achei e copiei para o lib da minha aplicação,

Valeu.

Paulo

AlineSzpaller

E este, alguém sabe?

“Erro:org.hibernate.HibernateException: Dialect class not found: org.hibernate.PostgreSQLDialect”

Já importei nas classes necessárias, as bibliotecas org.hibernate.* e org.hibernate.cfg.Configuration;

:-o

A

Galera,

Lamento ressuscitar este tópico mas pareceu-me o melhor local para colocar a minha duvida.

Estou usando o Hibernate 3.3.2.GA e uma base de dados Oracle

tenho duas maquinas diferentes mas com as mesmas configurações e quando gero código obtenho resultados diferentes.
para uma mesma entidade ele troca a ordem dos argumentos colocados no construtor

Exemplo:
hibernate.cfg.xml

<session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

        <property name="hibernate.connection.url">jdbc:oracle:thin:@[IP]:[PORT]:DEV26</property>
        <property name="hibernate.connection.username">user</property>
        <property name="hibernate.connection.password">pass</property>

        <property name="hibernatetool.metadatadialect">org.hibernate.cfg.reveng.dialect.OracleMetaDataDialect</property>
        <property name="current_session_context_class">thread</property>
    </session-factory>

sql da tabela - DDL

CREATE TABLE "TRAINNING"."ITEM" 
   (	"ID_ITEM" NUMBER(24,0) NOT NULL ENABLE, 
	"CODE" VARCHAR2(200 CHAR), 
	"NAME" VARCHAR2(200 CHAR), 
	"BLOCKED" VARCHAR2(1 CHAR), 
	"ID_ITEM_CATEGORY" NUMBER(24,0) NOT NULL ENABLE, 
	"ID_ITEM_UM" NUMBER(24,0) NOT NULL ENABLE, 
	"ID_ITEM_STATUS" NUMBER(24,0) NOT NULL ENABLE, 
	CONSTRAINT "ITM_PK" PRIMARY KEY ("ID_ITEM"),
	CONSTRAINT "ITM_BK" UNIQUE ("CODE"),
	CONSTRAINT "ITM_IC_FK" FOREIGN KEY ("ID_ITEM_CATEGORY")
	  REFERENCES "TRAINNING"."_ITEM_CATEGORY" ("ID_ITEM_CATEGORY") ENABLE, 
	CONSTRAINT "ITM_IUM_FK" FOREIGN KEY ("ID_ITEM_UM")
	  REFERENCES "TRAINNING"."_ITEM_UNIT_MEASURE" ("ID_ITEM_UNIT_MEASURE") ENABLE,
	CONSTRAINT "ITM_ISTAT_FK" FOREIGN KEY ("ID_ITEM_STATUS")
	  REFERENCES "TRAINNING"."ITEM_STATUS" ("ID_ITEM_STATUS") ENABLE
   ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS [telefone removido]
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
  TABLESPACE "TABLE_M" ;

como resultado tenho para o construtor da entidade:

Esperado (numa das maquinas tenho isto)

@Entity
@Table(name="ITEM",schema="TRAINNING")
public class Item extends itemGeneric 
{
	private static final long serialVersionUID = 1L;
	public Item(String code, PfwItemUnitMeasure pfwItemUnitMeasure, PfwItemCategory pfwItemCategory, PfwItemStatus pfwItemStatus)
	{	
		super(code, pfwItemUnitMeasure, pfwItemCategory, pfwItemStatus);
	}

Obtido (noutra tenho isto)

@Entity
@Table(name="ITEM",schema="TRAINNING")
public class Item extends itemGeneric 
{
	public Item(String code, PfwItemStatus pfwItemStatus, PfwItemCategory pfwItemCategory, PfwItemUnitMeasure pfwItemUnitMeasure)
	{	
		super(code, pfwItemStatus, pfwItemCategory, pfwItemUnitMeasure);
	}

A minha explicação é que na primeira aparece pela ordem de criação das tabelas…

pfwItemStatus, pfwItemCategory e pfwItemUnitMeasure sao FKs na tabela e pfwItemStatus aparece trocado com pfwItemUnitMeasure

Alguém sabe porque esta troca acontece ou como forçar a ordem?

Valeu

Miguel

A

Segundo testes q fiz, o problema

  • n é do JDBC driver
  • n é da BD/tabelas (a não ser q sejam efectuadas alterações)

aparenta ser de plugins do eclipse, mas n sei como resolver…

a solução pode ser forçar uma ordem alfabética, mas n é ideal

Criado 19 de maio de 2005
Ultima resposta 18 de nov. de 2010
Respostas 8
Participantes 5