Problema com Hibernate [RESOLVIDO]

9 respostas
brunorota

Olá galera

Estou com um problema, pesquisei pesquisei e não encontrei o porque do erro

Segue minhas classes para análise

@Entity
public class Produto {
	
	@Id
	@GeneratedValue
	private Integer codigo;
	private String nome;
	private Double valor;
	
	//Getters and Setters
}

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8" ?> 
  <!DOCTYPE hibernate-configuration (View Source for full doctype...)> 
- <hibernate-configuration>
- <session-factory name="">
  <property name="connection.url">jdbc:mysql://localhost/sistemas</property> 
  <property name="connection.username">root</property> 
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 
  <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> 
  <property name="connection.password">root</property> 
  <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property> 
- <!-- 
			thread is the short name for
			org.hibernate.context.ThreadLocalSessionContext and let Hibernate
			bind the session automatically to the thread
		

  --> 
  <property name="current_session_context_class">thread</property> 
- <!--  this will show us all sql statements 
  --> 
  <property name="hibernate.show_sql">true</property> 
- <!--  mapping files 
  --> 
  <mapping class="br.com.caelum.hibernate.Produto" /> 

  </session-factory>
  </hibernate-configuration>

meu HibernateFactory

public class HibernateConnectionFactory {


private static final SessionFactory sessionFactory;
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

static{
	try{
		sessionFactory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
	}catch(Throwable e){
		System.out.println("antes");
		e.printStackTrace();
		System.out.println("depois");
		throw new ExceptionInInitializerError(e);
	}
}

public static Session createSession(){
Session session = threadLocal.get();
session = sessionFactory.openSession();
return session;
}

}

E a classe para gravar os objeto

public class AdicionarProduto {

	public static void main(String args[]){
		
		Produto p = new Produto();
		p.setNome("Sopa");
		p.setValor(new Double(50));
		
		Session session = HibernateConnectionFactory.createSession();
		session.beginTransaction();
		
		session.save(p);
		
		session.getTransaction().commit();
		
		session.close();
	}
	
}

O hibernate.cfg.xml está na raiz do projeto

o erro é esse

org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
	at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1586)
	at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:1212)
	at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:107)
	at org.hibernate.cfg.Configuration.configure(Configuration.java:1520)
	at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:1194)
	at br.com.caelum.hibernate.HibernateConnectionFactory.<clinit>(HibernateConnectionFactory.java:15)
	at br.com.caelum.hibernate.AdicionarProduto.main(AdicionarProduto.java:13)
Caused by: org.dom4j.DocumentException: Error on line 1 of document  : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.depois

	at org.dom4j.io.SAXReader.read(SAXReader.java:482)
	at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1576)
	... 6 more
Exception in thread "main" java.lang.ExceptionInInitializerError
	at br.com.caelum.hibernate.HibernateConnectionFactory.<clinit>(HibernateConnectionFactory.java:20)
	at br.com.caelum.hibernate.AdicionarProduto.main(AdicionarProduto.java:13)
Caused by: org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
	at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1586)
	at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:1212)
	at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:107)
	at org.hibernate.cfg.Configuration.configure(Configuration.java:1520)
	at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:1194)
	at br.com.caelum.hibernate.HibernateConnectionFactory.<clinit>(HibernateConnectionFactory.java:15)
	... 1 more
Caused by: org.dom4j.DocumentException: Error on line 1 of document  : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.
	at org.dom4j.io.SAXReader.read(SAXReader.java:482)
	at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1576)
	... 6 more

Até agora não achei o problema

Se alguem puder ajudar

Ficarei grato

Att

9 Respostas

Guevara

Eu não uso MySQL, mas a linha do dialect não seria esta?

hibernate.dialect org.hibernate.dialect.MySQLDialect

O resto seria:

hibernate.connection.driver_class com.mysql.jdbc.Driver
hibernate.connection.url jdbc:mysql://localhost:porta/banco
hibernate.connection.username usuario
hibernate.connection.password

Acho que esta configuração pode ajudar:

<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testebd</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">senha</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
         
<mapping class="classeAqui"/>
<mapping class="outraClasseAqui"/>
         
</session-factory>
</hibernate-configuration>

Abraço!

brunorota

Opa

agora o erro foi esse olha

Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [br.com.caelum.hibernate.Produto]
	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
	at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
	at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2329)
	at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2836)
	at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
	at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
	at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
	at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
	at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
	at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
	at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
	at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:705)
	at org.hibernate.impl.SessionImpl.save(SessionImpl.java:693)
	at org.hibernate.impl.SessionImpl.save(SessionImpl.java:689)
	at br.com.caelum.hibernate.AdicionarProduto.main(AdicionarProduto.java:16)
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'sistemas.produto' doesn't exist
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
	at com.mysql.jdbc.Connection.execSQL(Connection.java:3256)
	at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1313)
	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1585)
	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1500)
	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1485)
	at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
	at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
	... 16 more

valew

Zeed01

Boa noite galera,

Posta como ficou seu hibernate.cfg agora e a sua classe Produto.

[]s

Guevara

Tabela “sistemas.produto” não existe.

Confere o que vc têm de classes mapeadas com o que existe de tabela no banco.

brunorota

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.connection.driver_class">com.mysql.jdbc.Driver</property>  
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sistemas</property>  
<property name="hibernate.connection.username">root</property>  
<property name="hibernate.connection.password">root</property>  
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
<property name="show_sql">true</property>  
           
<mapping class="br.com.caelum.hibernate.Produto"/>  
           
</session-factory>  
</hibernate-configuration>

a classe produto eu nao alterei

brunorota

a tabela produto nao existe mesmo

O hibernate nao cria a tabela quando ela nao existe?

Valew

brunorota

Opa com a tabela produto criada no banco deu certo

Obrigado a todos que ajudaram

Valew

Não tem um esquema no hibernate que ele cria as tabelas automaticamente?

Valew

Zeed01

Boa noite galera,

Para que ele faça isso vc deve setar a propriedade hbm2ddl.auto=update no seu hinernate,cfg

Acho que seria algo assim:

update

[]s

brunorota

Opa Zeed

É isso ae mesmo

Fumegou hehehe

VAlew mesmo

Muito obrigado

Até a proxima =)

Valew

Criado 1 de setembro de 2010
Ultima resposta 1 de set. de 2010
Respostas 9
Participantes 3