Teste com hibernate não funciona

15 respostas
E

Pessoal, estou iniciando os estudos com hibernate e estou utilizando o tutorial "Introdução ao hibernate 3" aqui do guj. Acontece que ao executar o teste com o arquivo Teste.java, acontece o seguinte erro:

Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException
at HibernateUtility.<clinit>(HibernateUtility.java:27)
at Teste.main(Teste.java:6)

Alguém sabe o que devo fazer? Envio o código Teste.java e HibernateUtility.java a seguir:
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Teste {
	public static void main(String[] args) {
		Session sessao = HibernateUtility.getSession(); //Abrindo uma sessão
		Transaction transaction = sessao.beginTransaction(); //Iniciando uma transação
		Curso curso = new Curso(); //Instanciando um objeto transiente
		curso.setNome("Desenvolvimento de Software"); //Preenchendo as propriedades do objeto
		curso.setDescricao("Curso só pra programadores");
		sessao.save(curso); //Transformando o objeto transiente em um objeto
		
		//persistente no banco de dados
		transaction.commit(); //Finalizando a transação
		sessao.close(); //Fechando a sessão
	}
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * @author Maurício
 *
 * Código desenvolvido por Maurício Linhares
 * 
 */
public class HibernateUtility {

    private static SessionFactory factory;
        
    static {
    	//Bloco estático que inicializa o Hibernate
    	try {
    	
        factory = new Configuration().configure().buildSessionFactory();
    	
    	} catch (Exception e) {
    		e.printStackTrace();
    		factory = null;
    	}
    }
    
    public static Session getSession() {
        //Retorna a sessão aberta
    	return factory.openSession();
    }
    
}

15 Respostas

R

Verifique o erro:

Você precisa adicionar o arquivo dom4j-xxx.jar em seu CLASSPATH.

Espero ter ajudado.

E

Bem, após ter configurado o CLASSPATH direitim, ele dá agora o seguinte erro:

09:48:48,359 WARN JDBCExceptionReporter:77 - SQL Error: 0, SQLState: 42P01
09:48:48,360 ERROR JDBCExceptionReporter:78 - ERROR: relation “curso” does not exist
Exception in thread “main” org.hibernate.exception.SQLGrammarException: could not fetch initial value for increment generator

De acordo com o tutorial, criei um arquivo Curso.hbm.xml que se relaciona com o arquivo Disciplina.hbm.xml. O que devo fazer, aonde devo “mexer” pra corrigir o erro?

R

Cole aqui sua classe Curso e Disciplina, bem como seus hbms, para que possa ser feita uma análise melhor do erro.

E

Curso.java:

import java.util.Set;

public class Curso {
 
	private String descricao;
	private String nome;
	private Set disciplinas;
	private Integer id;

	/**
	 * @return Returns the id.
	 */
	public Integer getId() {
		return id;
	}
	/**
	 * @param id The id to set.
	 */
	public void setId(Integer id) {
		this.id = id;
	}	
	
	/**
	 * @return Returns the descricao.
	 */
	public String getDescricao() {
		return descricao;
	}
	/**
	 * @param descricao The descricao to set.
	 */
	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}
	/**
	 * @return Returns the disciplinas.
	 */
	public Set getDisciplinas() {
		return disciplinas;
	}
	/**
	 * @param disciplinas The disciplinas to set.
	 */
	public void setDisciplinas(Set disciplinas) {
		this.disciplinas = disciplinas;
	}
	/**
	 * @return Returns the nome.
	 */
	public String getNome() {
		return nome;
	}
	/**
	 * @param nome The nome to set.
	 */
	public void setNome(String nome) {
		this.nome = nome;
	}
}

Curso.hbm.xml:

&lt?xml version="1.0" encoding="UTF-8"?&gt

&lt;!DOCTYPE hibernate-mapping 
	PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;

&lt;hibernate-mapping&gt;

	&lt;class name="Curso"&gt;
	
		&lt;id name="id"&gt;
			&lt;generator class="increment"/&gt;
		&lt;/id&gt;
		
		&lt;property name="nome"/&gt;
		&lt;property name="descricao"/&gt;
	
		&lt;set name="disciplinas"
			 inverse="true"
			 cascade="save-update"&gt;
		
			&lt;key column="Curso_id"/&gt;
			&lt;one-to-many class="Disciplina"/&gt;
		
		&lt;/set&gt;
	
	&lt;/class&gt;

&lt;/hibernate-mapping&gt;
E

classe Disciplina.java:

import java.util.Set;

public class Disciplina {
 
	private String nome;
	private String ementa;
	private Set turmas;
	private Curso curso;
	private Integer id;
	
	
	
	/**
	 * @return Returns the id.
	 */
	public Integer getId() {
		return id;
	}
	/**
	 * @param id The id to set.
	 */
	public void setId(Integer id) {
		this.id = id;
	}
	
	
	/**
	 * @return Returns the curso.
	 */
	public Curso getCurso() {
		return curso;
	}
	/**
	 * @param curso The curso to set.
	 */
	public void setCurso(Curso curso) {
		this.curso = curso;
	}
	/**
	 * @return Returns the ementa.
	 */
	public String getEmenta() {
		return ementa;
	}
	/**
	 * @param ementa The ementa to set.
	 */
	public void setEmenta(String ementa) {
		this.ementa = ementa;
	}
	/**
	 * @return Returns the nome.
	 */
	public String getNome() {
		return nome;
	}
	/**
	 * @param nome The nome to set.
	 */
	public void setNome(String nome) {
		this.nome = nome;
	}
	/**
	 * @return Returns the turmas.
	 */
	public Set getTurmas() {
		return turmas;
	}
	/**
	 * @param turmas The turmas to set.
	 */
	public void setTurmas(Set turmas) {
		this.turmas = turmas;
	}
}

Disciplina.hbm.xml:

&lt?xml version="1.0" encoding="UTF-8"?&gt

&lt;!DOCTYPE hibernate-mapping 
	PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;

&lt;hibernate-mapping&gt;

	&lt;class name="Disciplina"&gt;
		
		&lt;id name="id"&gt;
			&lt;generator class="increment"/&gt;
		&lt;/id&gt;
		
		&lt;property name="ementa"/&gt;
		&lt;property name="nome"/&gt;
		
		&lt;set name="turmas"
			 inverse="true"&gt;
		
			&lt;key column="Disciplina_id"/&gt;
			&lt;one-to-many class="Turma"/&gt;
		
		&lt;/set&gt;
		
		&lt;many-to-one 
				name="Curso"
				class="Curso"
				column="Curso_id"/&gt;
		
	&lt;/class&gt;

&lt;/hibernate-mapping&gt;
R

E a classe disciplina com seu hbm? Cole-a também fazendo favor.

[editado]Já está colada[/editado]

E

pronto…muito obrigado pela ajuda. qq coisa o id da tabela curso está incrementando automaticamente os valores. e o id da tablea Disciplina tb.

R

Ao final do seu hbm de disciplina na parte:

&lt;many-to-one 
 				name="Curso"
 				class="Curso"
 				column="Curso_id"/&gt;

Altere para:

&lt;many-to-one 
 				name="curso"
 				class="Curso"
 				column="Curso_id"/&gt;
marciobarroso

Vc precisa identificar no seu hibernat.cfg.xml as classes que podem ser persistidas.

Exemplo :

&lt?xml version='1.0' encoding='utf-8'?&gt
&lt;!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt;
	
&lt;hibernate-configuration&gt;

	&lt;session-factory&gt;
	
		&lt;property name="hibernate.dialect"&gt;org.hibernate.dialect.HSQLDialect&lt;/property&gt;
		&lt;property name="hibernate.connection.url"&gt;jdbc:hsqldb:file:tutoStrutsGujDB&lt;/property&gt;
		&lt;property name="hibernate.connection.driver_class"&gt;org.hsqldb.jdbcDriver&lt;/property&gt;
		&lt;property name="hibernate.connection.username"&gt;sa&lt;/property&gt;
		&lt;property name="hibernate.connection.password"&gt;&lt;/property&gt;

		&lt;property name="hibernate.show_sql"&gt;false&lt;/property&gt;
		&lt;property name="hibernate.hbm2ddl.auto"&gt;update&lt;/property&gt;
		&lt;property name="hibernate.cache.provider_class"&gt;org.hibernate.cache.HashtableCacheProvider&lt;/property&gt;
		&lt;property name="hibernate.show_sql"&gt;true&lt;/property&gt;
		&lt;property name="hibernate.generate_statistics"&gt;true&lt;/property&gt;
		&lt;property name="hibernate.use_sql_comments"&gt;true&lt;/property&gt;
		&lt;property name="hibernate.hbm2ddl.auto"&gt;update&lt;/property&gt;

 		[b]&lt;mapping class="br.com.guj.struts.tutorial.pojo.Usuario" /&gt;[/b]

	&lt;/session-factory&gt;

&lt;/hibernate-configuration&gt;

[]'s

E

continua o erro:

10:22:49,554 WARN JDBCExceptionReporter:77 - SQL Error: 0, SQLState: 42P01
10:22:49,555 ERROR JDBCExceptionReporter:78 - ERROR: relation “curso” does not exist
Exception in thread “main” org.hibernate.exception.SQLGrammarException: could not fetch initial value for increment generator

E

tentei postar por várias vezes o hibernate.cfg.xml e o guj deu erro:

An error has occurred.
For detailed error information, please see the HTML source code, and contact the forum Administrator.

org.htmlparser.nodes.RemarkNode

E

taí o meu hibernate.cfg.xml. será q tem algo de errado nele?

<!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.PostgreSQLDialect
		</property>
		<property 
			name="hibernate.connection.driver_class">
			org.postgresql.Driver
		</property>
		<property 
			name="hibernate.connection.url">
			jdbc:postgresql://localhost:5432/universidade
		<!--jdbc:mysql://localhost/hibernate?autoReconnect=true-->
		</property>
		<property 
			name="hibernate.connection.username">
			postgres
		</property>
		<property 
			name="hibernate.connection.password">
			netel
		</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="use_outer_join">true</property>	
        <property name="hibernate.generate_statistics">true</property>
        <property name="hibernate.use_sql_comments">true</property>
        	
		<mapping resource="Curso.hbm.xml"/>
		<mapping resource="Disciplina.hbm.xml"/>
		<mapping resource="Turma.hbm.xml"/>			
		<mapping resource="Pessoa.hbm.xml"/>	
		<mapping resource="Aluno.hbm.xml"/>		
		<mapping resource="Professor.hbm.xml"/>		
		<mapping resource="Endereco.hbm.xml"/>
			
	</session-factory>
</hibernate-configuration>
cado

o hibernate.cfg.xml ta no mesmo diretorio do Curso.hbm.xml??

Se nao estiver coloque o caminho completo

&lt;mapping resource="/caminho/do/hbm/Curso.hbm.xml"/&gt;

Mesma coisa para os outros

E

estão sim no mesmo diretório.

E

aí vai a lista de erros que acontecem:

11:16:11,642  WARN JDBCExceptionReporter:77 - SQL Error: 0, SQLState: 42P01
11:16:11,643 ERROR JDBCExceptionReporter:78 - ERROR: relation "curso" does not exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not fetch initial value for increment generator
	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
	at org.hibernate.id.IncrementGenerator.getNext(IncrementGenerator.java:107)
	at org.hibernate.id.IncrementGenerator.generate(IncrementGenerator.java:44)
	at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:98)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
	at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
	at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
	at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
	at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
	at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
	at Teste.main(Teste.java:12)
Caused by: org.postgresql.util.PSQLException: ERROR: relation "curso" does not exist
	at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:1525)
	at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1309)
	at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:188)
	at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:452)
	at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:354)
	at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:258)
	at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
	at org.hibernate.id.IncrementGenerator.getNext(IncrementGenerator.java:85)
	... 11 more

sendo que em Teste.java o erro se inicia em sessao.save(curso);

alguém pode ajudar a consertar isso?

Criado 29 de dezembro de 2006
Ultima resposta 29 de dez. de 2006
Respostas 15
Participantes 4