Simplesmente não consigo gerar a tabela pelo hibernate

30 respostas
jason_bourne

Pessoal,

Estou tentando criar a tabela pelo hibernate e não gera nenhuma msg de erro, mas tb não cria a tabela. Segue:

GeraTabelas.java

public class GeraTabelas {

	public static void main(String[] args) {

		Configuration configuration = new AnnotationConfiguration();
		configuration.configure();

		SchemaExport se = new SchemaExport(configuration);
		se.create(true, true);

		System.out.println("ok");

	}

}

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.password"></property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/banco</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<mapping class="br.org.minhaurl.jdbc.modelo.Usuario"/>

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

Usuario.java

@Entity
public class Usuario {

	@Id
	@GeneratedValue
	private long id;
	private String nome;
	private String usuario;
	private String senha;


	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
	public String getSenha() {
		return senha;
	}
	public void setSenha(String senha) {
		this.senha = senha;
	}
	public String getUsuario() {
		return usuario;
	}
	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}


}

30 Respostas

S

coloca isso no .cfg

<property name="hibernate.hbm2ddl.auto">create</property>

ele cria e recria o shema…

jason_bourne

soudaniel_01:
coloca isso no .cfg

<property name="hibernate.hbm2ddl.auto">create</property>

ele cria e recria o shema…

Mesma coisa :frowning:

jason_bourne

a única coisa q aparece é isso:

C

Crie o arquivo log4j.properties, coloque-o na pasta onde tem o código fonte, copie o conteúdo abaixo e cole no arquivo.

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=warn, stdout
log4j.logger.org.hibernate=debug
log4j.logger.org.hibernate.type=debug
log4j.logger.org.hibernate.tool.hbm2ddl=debug

Esses warnings sumirão e se der algum erro aparecerá no console.

jason_bourne

cesarherrera:
Crie o arquivo log4j.properties, coloque-o na pasta onde tem o código fonte, copie o conteúdo abaixo e cole no arquivo.

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=warn, stdout
log4j.logger.org.hibernate=debug
log4j.logger.org.hibernate.type=debug
log4j.logger.org.hibernate.tool.hbm2ddl=debug

Esses warnings sumirão e se der algum erro aparecerá no console.

Estranho, aparece como se tivesse sido criado, mas quando vou listar as tabelas não aparece nada. Segue o log:

felipealbuquerque

Deixa eu tentar adivinhar… você está utilizando o Eclipse, correto? Comigo, a mesma coisa acontece, mas somente do Eclipse. No NetBeans, as tabelas são geradas e aparecem na base de dados corretamente.
Eu também estou procurando uma solução para esse problema, mas ainda não encontrei. Espero que aqui consigamos encontrar alguma saída.

felipealbuquerque

Putz… tem um jeito de mudar o autocommit para true ou dar um commit? Pode ser isso!

jason_bourne

felipealbuquerque:

09:08:34,812 INFO DriverManagerConnectionProvider:45 - autocommit mode: false

Putz… tem um jeito de mudar o autocommit para true ou dar um commit? Pode ser isso!

Coloquei

<property name="hibernate.connection.autocommit">true</property>

e mesmo assim não vai:

jason_bourne

putz…q problema chato, nem tem erro no console nem nada… :frowning:

Marky.Vasconcelos

Mapeia na criação para ver se funciona

public class GeraTabelas {   
  
    public static void main(String[] args) {   
  
        AnnotationConfiguration configuration = new AnnotationConfiguration();   
        configuration.addAnnotedClass(br.org.minhaurl.jdbc.modelo.Usuario.class);
  
        SchemaExport se = new SchemaExport(configuration);   
        se.create(true, true);   
  
        System.out.println("ok");   
  
    }   
  
}

O pior que nunca tive esse problema com o cfg.xml

jason_bourne
Mark_Ameba:
Mapeia na criação para ver se funciona
public class GeraTabelas {   
  
    public static void main(String[] args) {   
  
        AnnotationConfiguration configuration = new AnnotationConfiguration();   
        configuration.addAnnotedClass(br.org.minhaurl.jdbc.modelo.Usuario.class);
  
        SchemaExport se = new SchemaExport(configuration);   
        se.create(true, true);   
  
        System.out.println("ok");   
  
    }   
  
}

O pior que nunca tive esse problema com o cfg.xml

Aparece esse erro:


10:54:15,953 INFO Version:15 - Hibernate Annotations 3.2.1.GA
10:54:15,984 INFO Environment:514 - Hibernate 3.2.5
10:54:15,984 INFO Environment:547 - hibernate.properties not found
10:54:15,984 INFO Environment:681 - Bytecode provider name : cglib
10:54:16,000 INFO Environment:598 - using JDK 1.4 java.sql.Timestamp handling
Exception in thread "main" org.hibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect.
at org.hibernate.dialect.Dialect.instantiateDialect(Dialect.java:233)
at org.hibernate.dialect.Dialect.getDialect(Dialect.java:211)
at org.hibernate.dialect.Dialect.getDialect(Dialect.java:226)
at org.hibernate.tool.hbm2ddl.SchemaExport.(SchemaExport.java:86)
at org.hibernate.tool.hbm2ddl.SchemaExport.(SchemaExport.java:61)
at br.org.xxxxxxxxx.hibernate.GeraTabelas.main(GeraTabelas.java:21)

Mas o dialect ta setado:

org.hibernate.dialect.MySQLDialect
dc.rec1

Ja aconteceu algo similar comigo. O que estava errado eram os imports. Tinha importado a classe Persistence de algum pacote do Hibernate e tinha que ser de algum pacote do javax. Se fizer ctrl + shift + o no Eclipse, aparecem os dois.

jason_bourne

Mas eu to importando tudo do javax:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Usuario {

	@Id
	@GeneratedValue
	private long id;
	private String nome;
	private String usuario;
	private String senha;


	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
	public String getSenha() {
		return senha;
	}
	public void setSenha(String senha) {
		this.senha = senha;
	}
	public String getUsuario() {
		return usuario;
	}
	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}


}
Marky.Vasconcelos

Acho que o AnnotedClass só funciona com o hibernate.properties

jason_bourne

Sera que é um problema de versão da lib do hibernate?

Marky.Vasconcelos

Não sei, nunca tive problemas similares. ^^

jason_bourne

Ninguem sabe o motivo de estar ocorrendo isso?

felipealbuquerque

Você adicionou o jar do SGBD? Aqui eu tinha (burramente) me esquecido de adicionar o jar…

jason_bourne

Sim, ja tinha

jason_bourne

Qual é a versão do hibernate e o hibernate-annotations q vcs usam?

I

Estou com um problema, o log4j não gera o schema, não dá erro, mas simplesmente na gera…trabalho no ambiente windows…com eclipse. Trabalhava no linux com os mesmos jars e funcionava perfeitamente…soh no windows q dah esse erro…vcs podem me ajudar??

klebernss

Você disse que ele cria e recria. Verifique se vc está colocando update ou create no hibernate:

[color=darkblue]<property name=“hbm2ddl.auto”>update</property>[/color]

Outra coisa, pq vc ao inves não constrói as tabelas assim:

[color=darkred]<?xml version=“1.0”?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>
<hibernate-mapping package=“cadastro”>

&lt;class name="cadastro.Cliente" table="cliente"&gt;
    &lt;id name="codigo" &gt;
        &lt;generator class="native"/&gt;
    &lt;/id&gt;
    &lt;property name="nome" length="50" /&gt;
    &lt;property name="email"/&gt;
    &lt;property name="nascimento" type="timestamp" column="nascimento"/&gt;
    &lt;property name="cpf" /&gt;
    &lt;property name="cep"/&gt;
    &lt;property name="rua"/&gt;
    &lt;property name="bairro"/&gt;
    &lt;property name="cidade"/&gt;
    &lt;property name="estado"/&gt;
    &lt;property name="pontoReferencia"/&gt;
    &lt;property name="recebeInformacao" &gt;
    
    &lt;/property&gt;
    
&lt;/class&gt;

</hibernate-mapping>[/color]

Basta usar o hibernate mapping:

<mapping resource=“cadastro/Cliente.hbm.xml”/>

Espero ter ajudado

I

Mas eu tow usando anotação.

I

Olha, configurei tudo…e o schema tah sendo gerado…mas quando abro o arquivo do schema, simplesmente não tem nada escrito…tow batendo cabeça desde ontem.

klebernss

Se não der com o update, cria primeiro como create e depois muda pra update (no Hibernate).

<property name=“hbm2ddl.auto”>update</property>

I

jah identifiquei que o problema é no windows mesmo. Tenho q reconfigurar o hibernate. Pois eu trabalhava em ambiente linux e migrei para windows essa semana!

Consigo gerar o schema, mas nada aparece

J

Cara, estava com o mesmo problema.

Troquei os importes para

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

e funcionou perfeitamente, criando a tabela.

No meu caso estava usando firebird.

Abraço.

R

Caros,

Estou exatamente com o mesmo problema, o eclipse parece criar a tabela, mas não cria

rodnei22:27:44,719  INFO Version:15 - Hibernate Annotations 3.4.0.GA

22:27:44,762  INFO Environment:543 - Hibernate 3.3.0.SP1

22:27:44,771  INFO Environment:561 - loaded properties from resource hibernate.properties: {hibernate.connection.username=root, hibernate.connection.password=<strong><strong>, hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect, hibernate.connection.url=jdbc:mysql://localhost:3306/estadio, hibernate.bytecode.use_reflection_optimizer=false, hibernate.connection.driver_class=com.mysql.jdbc.Driver, hibernate.hbm2ddl.auto=validate   }

22:27:44,778  INFO Environment:709 - Bytecode provider name : javassist

22:27:44,812  INFO Environment:627 - using JDK 1.4 java.sql.Timestamp handling

22:27:45,004  INFO Version:14 - Hibernate Commons Annotations 3.1.0.GA

22:27:45,097  INFO Dialect:175 - Using dialect: org.hibernate.dialect.MySQLInnoDBDialect

22:27:45,346  INFO AnnotationConfiguration:369 - Hibernate Validator not found: ignoring

22:27:45,362  INFO SchemaExport:226 - Running hbm2ddl schema export

22:27:45,364  INFO SchemaExport:251 - exporting generated schema to database

22:27:45,371  INFO DriverManagerConnectionProvider:64 - Using Hibernate built-in connection pool (not for production use!)

22:27:45,372  INFO DriverManagerConnectionProvider:65 - Hibernate connection pool size: 20

22:27:45,373  INFO DriverManagerConnectionProvider:68 - autocommit mode: false

22:27:45,394  INFO DriverManagerConnectionProvider:103 - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/estadio

22:27:45,395  INFO DriverManagerConnectionProvider:109 - connection properties: {user=root, password=</strong></strong>}

22:27:46,136  INFO SchemaExport:310 - Executing import script: /import.sql

22:27:46,137  INFO SchemaExport:268 - schema export complete

22:27:46,140  INFO DriverManagerConnectionProvider:170 - cleaning up connection pool: jdbc:mysql://localhost:3306/estadio

Alguem ai conseguiu resolver este problema???

supertchuco

Kra, não sei se ainda precisa ,mas eu estava com o mesmo problema e consegui resolver, o problema esta nos imports, ou seja , use os seguintes imports :

na classe que vai ser o modelo da tabela use :

import java.io.Serializable;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

na classe que vai criar a tabela use :

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

e na classe teste para inserir use :

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.AnnotationConfiguration;

import org.hibernate.classic.Session;

Para mim resolveu, consegui criar e até inserir dados…

Qualquer coisa me manda um e-mail que tento te ajudar…

carolino

Tenho a seguinte extrutura no meu persistence.xml

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!-- Persistence deployment descriptor for dev profile --&gt;
&lt;persistence xmlns="http://java.sun.com/xml/ns/persistence" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" 
             version="1.0"&gt;
             
   &lt;persistence-unit name="sys3e" transaction-type="JTA"&gt;
      &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
      &lt;jta-data-source&gt;java:/sys3eDatasource&lt;/jta-data-source&gt;
      &lt;properties&gt;
         &lt;property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/&gt;
         &lt;property name="hibernate.hbm2ddl.auto" value="create"/&gt;
         &lt;property name="hibernate.show_sql" value="true"/&gt;
         &lt;property name="hibernate.format_sql" value="true"/&gt;
         &lt;!-- Only relevant if Seam is loading the persistence unit (Java SE bootstrap) --&gt;
         &lt;property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/&gt;
      &lt;/properties&gt;
   &lt;/persistence-unit&gt;
 &lt;/persistence&gt;

e minhas entidades estão mapeadas com import javax.persistence nos lugares certos,
só que mesmo assim ele não consegue gerar minhas tabelas quando estou
subindo o servidor (Jboss-4.2.3)

Alguem tem mais alguma idéia?

Obrigado a todos que ajudarem

Criado 3 de dezembro de 2007
Ultima resposta 20 de abr. de 2011
Respostas 30
Participantes 12