Hibernate tá dificil

9 respostas
D

Olá pessoal!
Estou aprendendo a mexer com o hibernate mas ele insiste em dar erro nessa linha que chama o hibernate.cfg.xml:

/*
 * Main.java
 *
 * Created on 29 de Março de 2007, 09:03
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.acme.helloworld;

import com.acme.helloworld.Aluno;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author danielm
 */
public class Main {

    private static SessionFactory factory;
    
    public static void main(String args[]){
            Session session = getSession();
            Transaction transaction = session.beginTransaction();
            
            Aluno aluno = new Aluno();
            aluno.setNome("Tião");
            aluno.setMatricula(2003456);
            aluno.setCpf(838392722);
            
            session.save(aluno);
            transaction.commit();
            session.close();
        
    }
    

    static {
        try {
            factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        } catch (Exception e) {
            e.printStackTrace();
            factory = null;
        }
    }
    
    public static Session getSession() {
        return factory.openSession();
    }
    
}

Config do hibernate:

<!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">
org.gjt.mm.mysql.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://inf011:3306/danieltestes?autoReconnect=true
</property>
<property name="hibernate.connection.username">
developer
</property>
<property name="hibernate.connection.password">
ecmdeveloper
</property>
<!-- Condiguração do c3p0 -->
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<!-- Configurações de debug -->
<property name="show_sql">true</property>
<property name="hibernate.generate_statistics">true</property>
<property name="hibernate.use_sql_comments">true</property>
<mapping resource="Aluno.hbm.xml"/>
</session-factory>
</hibernate-configuration>

O erro que ele dá é esse:

init:
deps-jar:
compile:
run:
java.lang.NoClassDefFoundError: org/dom4j/DocumentException
        at com.acme.helloworld.Main.<clinit>(Main.java:46)
Exception in thread "main" 
Java Result: 1
EXECUTADO COM SUCESSO (tempo total: 0 segundos)

9 Respostas

R

Coloca a mensagem e o StackTrace da Exception, senão “Hibernate tá dificil” de ajudar.

Dica do dia: Busque pela mensagem de erro no forum, pois deve ter muito “material” de ajuda nele.

Roger Leite

jamikas

Você tem que mapear o seu entityBean “Aluno no xml de config”.

D

Olá Roger! É isso:

init:
deps-jar:
compile:
run:
java.lang.NoClassDefFoundError: org/dom4j/DocumentException
at com.acme.helloworld.Main.(Main.java:46)
Exception in thread "main"
Java Result: 1
EXECUTADO COM SUCESSO (tempo total: 0 segundos)

ps.: Você tá engraçadinho hoje!

D

Olá jamikas! Como faz isso? Eu tenho um xml do aluno separado.

<?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="com.acme.helloworld.Aluno" table="aluno">
        <id name="id">
            <generator class="increment"/>
        </id>
        <property name="matricula" type="int"/>
        <property name="nome"/>
        <property name="cpf" type="int"/>
    </class>
</hibernate-mapping>

U bens dele:

/*
 * Aluno.java
 *
 * Created on 29 de Março de 2007, 08:22
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.acme.helloworld;

/**
 *
 * @author danielm
 */
public class Aluno {
    private int id;
    private int matricula;
    private String nome;
    private int cpf;
    
    public void Aluno(){}
    
    public long getCpf() {
        return cpf;
    }
    
    public void setCpf(int cpf) {
        this.cpf = cpf;
    }
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public int getMatricula() {
        return matricula;
    }
    
    public void setMatricula(int matricula) {
        this.matricula = matricula;
    }
    
    public String getNome() {
        return nome;
    }
    
    public void setNome(String nome) {
        this.nome = nome;
    }
}
jamikas

ao inves de maper o seu xml, vc pode maper a classe do entityBean direto com o seguinte comando: , vc esta utilizando chave primaria na sua tabela? pois não vi anotação no seu entityBean que demonstre isso!

D

Eu estou sim é o id. Eu mandei importar outros arquivos jar que vi no tutorial e ele me retornou outro erro:

init:
deps-jar:
Copying 2 files to C:\Documents and Settings\danielm\Meus documentos\programas\HelloWorld\build\classes
compile:
run:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
org.hibernate.MappingException: Resource: /com/acme/helloworld/Aluno.hbm.xml not found
        at org.hibernate.cfg.Configuration.addResource(Configuration.java:512)
        at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1506)
        at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1474)
        at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1453)
        at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1427)
        at org.hibernate.cfg.Configuration.configure(Configuration.java:1347)
        at com.acme.helloworld.Main.<clinit>(Main.java:46)
Exception in thread "main" java.lang.NullPointerException
        at com.acme.helloworld.Main.getSession(Main.java:54)
        at com.acme.helloworld.Main.main(Main.java:29)
Java Result: 1
EXECUTADO COM SUCESSO (tempo total: 0 segundos)

Parece que ele não reconheceu a entidade Aluno. Eu fiz como você pediu e deu o mesmo prob.

R

Não me leva a mal, mas eu tento ser engraçadinho todo dia ! Hehe. Desculpa eu não quis te ofender.

Seguindo a minha dica do dia, tente essa solução:

De acordo com o RicardoLuis (http://www.guj.com.br/posts/list/52425.java)

Você deve adicionar o arquivo dom4j-xxx.jar em seu classpath.

Em caso de sucesso ou não (pode acontecer de mudar a exception), posta pra nós.

[]s
Roger Leite

D

Eu já tinha adicionado esse jar. Ele apenas não está conseguindo localizar o meu Aluno.hbm.xml. Está tudo no mesmo pacote. Será que devo especificar msm assim?

D

Consegui resolver. Eu não especifiquei corretamente:
Assim:
com/acme/helloworld/Aluno.hbm.xml
E não assim:
/com/acme/helloworld/Aluno.hbm.xml

Criado 29 de março de 2007
Ultima resposta 29 de mar. de 2007
Respostas 9
Participantes 3