Hibernate pedindo pinico!ajudem por favor!

15 respostas
W

Bem vamos lá, to a uns 2 dias neste mesmo erro básico ... ja li um bucado sobre, cada um da uma solução mas de nda adianta, se alguem souber de algum jeito algo q de pra fazer, eu agradeço muitooo muitoo mesmo pq to quase largando mão do hibernate ... ou do netbeans ... ^^

vamo la:

Esse é o erro :
run-main:
04/10/2008 16:56:31 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.5
04/10/2008 16:56:31 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
04/10/2008 16:56:31 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
04/10/2008 16:56:31 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
04/10/2008 16:56:31 org.hibernate.cfg.Configuration addClass
INFO: Reading mappings from resource: logar/User.hbm.xml
04/10/2008 16:56:31 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource: logar/User.hbm.xml
04/10/2008 16:56:31 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: logar.User -> user
04/10/2008 16:56:31 org.hibernate.connection.UserSuppliedConnectionProvider configure
WARNING: No connection properties specified - the user must supply JDBC connections
Exception in thread "main" org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
        at org.hibernate.dialect.DialectFactory.determineDialect(DialectFactory.java:57)
        at org.hibernate.dialect.DialectFactory.buildDialect(DialectFactory.java:39)
        at org.hibernate.cfg.SettingsFactory.determineDialect(SettingsFactory.java:426)
        at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:128)
        at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
        at logar.Main.main(Main.java:39)
Java Result: 1

Esse é o arquivo Main.class q usei pra fazer ot este mais simples possível.

public class Main {
    private SessionFactory fabricaSessoes;
  /** Creates a new instance of Main */
  
  public void testeInsercao() {
    Session sessao = fabricaSessoes.openSession();
    org.hibernate.Transaction transacao = sessao.beginTransaction();
    User user = new User("Walter", "1234","[email removido]",2);
    sessao.save(user);
    transacao.commit();
    sessao.close();    
  }
  
  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    
      final Main test = new Main();
    
    Configuration cfg = new Configuration().addClass(User.class);
    
    test.fabricaSessoes = cfg.buildSessionFactory();
    
    test.testeInsercao();
  }


}
Esse o User.hbn.xml :
<hibernate-mapping>
  <class dynamic-insert="false" dynamic-update="false" mutable="true" 
  name="logar.User" optimistic-lock="version" polymorphism="implicit" 
  select-before-update="false" table="user">
      
      <id 
      name="userid" 
      column="USERID" 
      type="int">
          <generator class="increment"/>
      </id>
      
      <property 
      name="login"
      column="LOGIN"
      type="string"
      />
      
      <property 
      name="senha"
      column="SENHA"
      type="string"
      />
      
      <property 
      name="email"
      column="EMAIL"
      type="string"
      />
      
      <property 
      name="nivel"
      column="NIVEL"
      type="int"
      />
  </class>
  
</hibernate-mapping>

User.java sem os gets e sets

package logar;

/**
 *
 * @author walter
 */

public class User {
    private int userid;
    private String login;
    private String senha;
    private String email;
    private int nivel;
    
    public User(String login, String senha, String email, int nivel) {
    this.login = login;
    this.senha = senha;
    this.email = email;
    this.nivel = nivel;
  }

uma imagem de como q ta o negócio ... taquei o hibernate.cfg.xml em alguns lugares mais nda ...
[img=http://img158.imageshack.us/img158/2840/imagemhz9.th.jpg][img=http://img158.imageshack.us/images/thpix.gif]

ai vai o XML do hibernate ....
<?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 name="session1">
    <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/usuarios</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">admin</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping resource="logar/User.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

[]´s

15 Respostas

Marky.Vasconcelos
Hibernate Dialect must be explicitly set

falta alguma linha no xml mostrando qual o dialeto a ser usado pro banco

Cara e pra voce não se complicar com tanto xml, pesquise sobre Hibernate Annotations é tudo mais fáçil(Na minha opnião pleo menos)

W

Coloquei o codigo do arquivo de configuracao …
o dialeto nao seria aquele mesmo !? to usando mysql …
Aproveitando já que você comentou … é mais vantajoso o annotations mesmo !? … ou a diferença seria só a nao utilizacao de xml ?
[]s e vlw o comentario …

W

Alguem da uma mao ai gente … ja tentei troca o dialect por outros do mysql, mas nda … quem tiver alguma ideia do q seja … eu fico agradecido ! !
[]´s !

Mauricio_Linhares

O seu main deveria ser assim:

[code=java]public class Main {

private SessionFactory fabricaSessoes;

/** Creates a new instance of Main */
public void testeInsercao() {

Session sessao = fabricaSessoes.openSession();

org.hibernate.Transaction transacao = sessao.beginTransaction();

User user = new User(Walter, <a>1234,"[email removido]</a>",2);

sessao.save(user);

transacao.commit();

sessao.close();

}

/**

  • @param args the command line arguments
    */
    public static void main(String[] args) {

    final Main test = new Main();

Configuration cfg = new Configuration().addClass(User.class);

test.fabricaSessoes = cfg.configure().buildSessionFactory(); //você tem que chamar configure() pra dizer ao Hibernate que ele tem que ler o hibernate.cfg.xml

test.testeInsercao();

}
}
W

Ola maurício, valeu a dica mais ainda não era esse meu problema … continua dando o mesmo erro ! =/
Uso netbeans 6.1 … instalei o plugin do hibernate … se essa informacao ajudar …
Se alguem tiver alguma dica por favor…
[]´s

rodrigo_gomes

cara,

o arquivo hibernate.cfg.xml realmente está no classpath de seu projeto?
Parece que ele nao está sendo lido…

W

Ola ROdrigo, ele tava na posição default … criei o projeto e ele aparece na pasta Arquivos de Configuracao e dentro de Pacotes de codigos-fonte /pacotes-padrao … entao vi o erro e sai copiando o hibernate.cfg.xml pra tdo quanto era lugar … como mostra na figura.
Eu devo colocar ele em algum lugar especifico? Que lugar é exatamente ?..
[]´s

limaand

porque você usa annotations é bem mais prático e eficiente visite este site www.jeebrasil.com.br [b] :smiley:

W

É vo fazer isso … dar uma estudada em annotations … por sinal muito bom o material que ta la no www.jeebrasil.com.br … parabens pro pessoal de la ! =)

fbmanhani

Tente deixar o seu hibernate.cfg.xml como este exemplo, funciona em um projetinho meu aqui... feito em Netbeans tambem. O arquivo deve estar na pasta src do projeto.
Abrax.

<?xml version="1.0" encoding="utf-8" ?> 
  <!DOCTYPE hibernate-configuration (View Source for full doctype...)> 
- <hibernate-configuration>
- <session-factory>
- <!--  Database connection settings 
  --> 
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 
  <property name="connection.url">jdbc:mysql://127.0.0.1:3306/projeto</property> 
  <property name="connection.username">user</property> 
  <property name="connection.password">senha</property> 
- <!--  JDBC connection pool (use the built-in) 
  --> 
  <property name="connection.pool_size">10</property> 
- <!--  SQL dialect 
  --> 
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 
- <!--  Echo all executed SQL to stdout 
  --> 
  <property name="show_sql">true</property> 
  <mapping resource="cidade.hbm.xml" /> 
  </session-factory>
  </hibernate-configuration>
faelcavalcanti

provavelmente é o nome da propriedade [hibernate.dialect] para [dialect]

W

Ae galera ... bem ... tentei tentei e nda deu certo .... =/
fiquei "P" da vida e formatei a maquina huahuahua ...
E sei la por q cargas d´agua o bixo resolveu funfa .... vai entender ... enfim ...
Queria agradecer a tdos ! ! Vlw gente ! ;)

Bemmm .... se n for abusar do conhecimento de vcs ! ! meu problema é outro agora ... O hibernate ta rodando ... porém ele gera vários INFO´S ... Esses infos são só informes mesmo ou é algum tipo de warming !? aqui ó
07/10/2008 01:21:04 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.5
07/10/2008 01:21:04 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
07/10/2008 01:21:04 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
07/10/2008 01:21:04 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
07/10/2008 01:21:05 org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
07/10/2008 01:21:05 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
07/10/2008 01:21:05 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : logar/person.hbm.xml
07/10/2008 01:21:05 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: logar.Person -> person
07/10/2008 01:21:05 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : logar/Student.hbm.xml
07/10/2008 01:21:05 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: logar.Student -> student
07/10/2008 01:21:05 org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
07/10/2008 01:21:05 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
07/10/2008 01:21:05 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 20
07/10/2008 01:21:05 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
07/10/2008 01:21:05 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/teste
07/10/2008 01:21:05 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {user=root, password=****}
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: RDBMS: MySQL, version: 5.0.67-community-nt
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.5 ( Revision: ${svn.Revision} )
07/10/2008 01:21:05 org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
07/10/2008 01:21:05 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
07/10/2008 01:21:05 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/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): enabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 2
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL inserts for batching: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
07/10/2008 01:21:05 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JPA-QL strict compliance: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.NoCacheProvider
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
07/10/2008 01:21:05 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Named query checking : enabled
07/10/2008 01:21:05 org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
07/10/2008 01:21:06 org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
Hibernate: select max(id) from person
Hibernate: select max(id) from student
Hibernate: insert into person (cname, id) values (?, ?)
Hibernate: insert into student (school, grade, id) values (?, ?, ?)
CONSTRUÍDO COM SUCESSO (tempo total: 1 segundo)

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.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/teste</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">admin</property>
    <property name="hibernate.show_sql">true</property>
    <mapping resource="logar/person.hbm.xml"/>
    <mapping resource="logar/Student.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Meu arquivo de teste ...

public class main {

    public static void main(String[] args) {

        // Set up database tables
        // HibernateUtil.droptable("drop table person");
        //   HibernateUtil.setup("create table person ( id int, cname VARCHAR(20))");
        // Create SessionFactory and Session object
        SessionFactory sessions = new Configuration().configure().buildSessionFactory();
        Session session = sessions.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            // Create a Person object and save it
            Person p1 = new Person(1, "altair");
            //p1.setName("walter gsdgsg filho");
            session.save(p1);

            Student a1 = new Student();
            a1.setGrade("A");
            a1.setSchool("Nazaré");
            session.save(a1);

            // Retrieve the person objects
            //   Person person = (Person) session.get(Person.class, p1.getId());
            //   System.out.println("First person retrieved = " + person.getName());
            //   person = (Person) session.get(Person.class, p2.getId());
            //   System.out.println("Second person retrieved = " + person.getName());

            tx.commit();
            tx = null;
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Desde já agradeço !!! ;)

fbmanhani

walterbraga33:
Ae galera … bem … tentei tentei e nda deu certo … =/
fiquei “P” da vida e formatei a maquina huahuahua …
E sei la por q cargas d´agua o bixo resolveu funfa … vai entender … enfim …
Queria agradecer a tdos ! ! Vlw gente ! :wink:

Bemmm … se n for abusar do conhecimento de vcs ! ! meu problema é outro agora …
O hibernate ta rodando … porém ele gera vários INFO´S …
Esses infos são só informes mesmo ou é algum tipo de warming !?

Neste caso são apenas informativos mesmo. ^^

Boa sorte aí com seu projeto.

[]'s

faelcavalcanti

danousse, chegastes a este ponto :smiley:

W

Poise pra você ver, mas enfim o importante é que no fim deu certo …
vlw por tdas as respostas ! :wink:
[]´s

Criado 4 de outubro de 2008
Ultima resposta 8 de out. de 2008
Respostas 15
Participantes 7