Gerar Tabelas com Hibernate e Annotations

21 respostas
D

Tenho uma Classe Produto, e criei uma Classe para criar a tabela (DDL) automaticamente em meu Banco (MySQL), utilizando Hibernate e Annotations.
O aplicativo roda corretamente, mas não cria a tabela no banco. Alguém poderia me ajudar?

Classe Produto:
import java.io.Serializable;

import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Column;

import org.hibernate.annotations.Entity;


@Entity
public class Produto implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Long id;
	private String nome;
	private String descricao;
	private Double preco;
	
	@Column(name="descricao",nullable=true,length=50)
	// (name=”descricao”, nullable = true, length = 50)
	public String getDescricao() {
		return descricao;
	}
	@Id @GeneratedValue
	public Long getId() {
		return id;
	}
	public String getNome() {
		return nome;
	}
	public Double getPreco() {
		return preco;
	}
	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
	public void setPreco(Double preco) {
		this.preco = preco;
	}
}
Classe Gerar Tabela Produto:
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class GeraTabelas {

	public static void create(AnnotationConfiguration cfg) {
		new SchemaExport(cfg).create(true, true);		
	}

	public static void main(String[] args) {

		// Cria uma configuração para a classe Produto
		AnnotationConfiguration cfg = new AnnotationConfiguration();
		cfg.addAnnotatedClass(Produto.class);
		create(cfg);		
	}
}
hibernate.properties:
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost/jteste
hibernate.connection.username = root
hibernate.connection.password =

Saida:


2006-07-24 13:01:08,483 INFO cfg.annotations.Version -> Hibernate Annotations 3.2.0.CR1
2006-07-24 13:01:08,514 INFO hibernate.cfg.Environment -> Hibernate 3.1 rc3
2006-07-24 13:01:08,514 INFO hibernate.cfg.Environment -> loaded properties from resource hibernate.properties: {hibernate.connection.username=root, hibernate.connection.password=****, hibernate.cglib.use_reflection_optimizer=true, hibernate.dialect=org.hibernate.dialect.MySQLDialect, hibernate.connection.url=jdbc:mysql://localhost/jteste, hibernate.connection.driver_class=com.mysql.jdbc.Driver}
2006-07-24 13:01:08,576 INFO hibernate.cfg.Environment -> using CGLIB reflection optimizer
2006-07-24 13:01:08,576 INFO hibernate.cfg.Environment -> using JDK 1.4 java.sql.Timestamp handling
2006-07-24 13:01:08,873 INFO hibernate.dialect.Dialect -> Using dialect: org.hibernate.dialect.MySQLDialect
2006-07-24 13:01:08,967 DEBUG hibernate.cfg.AnnotationConfiguration -> Execute first pass mapping processing
2006-07-24 13:01:09,076 DEBUG hibernate.cfg.AnnotationConfiguration -> Process hbm files
2006-07-24 13:01:09,076 DEBUG hibernate.cfg.AnnotationConfiguration -> Process annotated classes
2006-07-24 13:01:09,076 DEBUG hibernate.cfg.AnnotationConfiguration -> processing manytoone fk mappings
2006-07-24 13:01:09,076 INFO hibernate.cfg.Configuration -> processing extends queue
2006-07-24 13:01:09,076 INFO hibernate.cfg.Configuration -> processing collection mappings
2006-07-24 13:01:09,076 INFO hibernate.cfg.Configuration -> processing association property references
2006-07-24 13:01:09,076 INFO hibernate.cfg.Configuration -> processing foreign key constraints
2006-07-24 13:01:09,092 DEBUG hibernate.cfg.AnnotationConfiguration -> Execute first pass mapping processing
2006-07-24 13:01:09,092 DEBUG hibernate.cfg.AnnotationConfiguration -> Process hbm files
2006-07-24 13:01:09,092 DEBUG hibernate.cfg.AnnotationConfiguration -> Process annotated classes
2006-07-24 13:01:09,092 DEBUG hibernate.cfg.AnnotationConfiguration -> processing manytoone fk mappings
2006-07-24 13:01:09,092 INFO hibernate.cfg.Configuration -> processing extends queue
2006-07-24 13:01:09,092 INFO hibernate.cfg.Configuration -> processing collection mappings
2006-07-24 13:01:09,092 INFO hibernate.cfg.Configuration -> processing association property references
2006-07-24 13:01:09,092 INFO hibernate.cfg.Configuration -> processing foreign key constraints
2006-07-24 13:01:09,092 INFO tool.hbm2ddl.SchemaExport -> Running hbm2ddl schema export
2006-07-24 13:01:09,092 DEBUG tool.hbm2ddl.SchemaExport -> import file not found: /import.sql
2006-07-24 13:01:09,092 INFO tool.hbm2ddl.SchemaExport -> exporting generated schema to database
2006-07-24 13:01:09,108 INFO hibernate.connection.DriverManagerConnectionProvider -> Using Hibernate built-in connection pool (not for production use!)
2006-07-24 13:01:09,108 INFO hibernate.connection.DriverManagerConnectionProvider -> Hibernate connection pool size: 20
2006-07-24 13:01:09,108 INFO hibernate.connection.DriverManagerConnectionProvider -> autocommit mode: false
2006-07-24 13:01:09,108 INFO hibernate.connection.DriverManagerConnectionProvider -> using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/jteste
2006-07-24 13:01:09,108 INFO hibernate.connection.DriverManagerConnectionProvider -> connection properties: {user=root, password=}
2006-07-24 13:01:09,108 DEBUG hibernate.connection.DriverManagerConnectionProvider -> total checked-out connections: 0
2006-07-24 13:01:09,108 DEBUG hibernate.connection.DriverManagerConnectionProvider -> opening new JDBC connection
2006-07-24 13:01:09,530 DEBUG hibernate.connection.DriverManagerConnectionProvider -> created connection to: jdbc:mysql://localhost/jteste, Isolation Level: 4
2006-07-24 13:01:09,530 INFO tool.hbm2ddl.SchemaExport -> schema export complete
2006-07-24 13:01:09,530 DEBUG hibernate.connection.DriverManagerConnectionProvider -> returning connection to pool, pool size: 1
2006-07-24 13:01:09,530 INFO hibernate.connection.DriverManagerConnectionProvider -> cleaning up connection pool: jdbc:mysql://localhost/jteste

21 Respostas

T

Blz.

Cara, como está configurado o seu hibernate.cfg.xml?

Exemplo:

<?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>
 		<mapping class="br.com.seupacote.modelo.Produto" />

	</session-factory>

</hibernate-configuration>

A sua conexão funcionou?

Outra coisa, na anotação da sua classe Produto, segue um exemplo:

Exemplo:

import javax.persistence.Entity;
import javax.persistence.GeneratorType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Produto {
	private Long id;
	private String descricao;
	private Categoria categoria;
	
	@ManyToOne
	public Categoria getCategoria() {
		return categoria;
	}
	public void setCategoria(Categoria categoria) {
		this.categoria = categoria;
	}
	public String getDescricao() {
		return descricao;
	}
	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}
	@Id(generate=GeneratorType.AUTO)
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
}

Espero ter ajudado,

Qualquer coisa, poste o que aconteceu novamente.

Valeu,

Tubarão - UDIA / MG

D

Ola Tubarão.

Muito Obrigado, sua atenção.

Para conexão, estou usando o “hibernate.properties”.
Estou conectando normalmente, através de um factory.
Simplesmente, não consigo criar a tabela.

Fiz algumas modificações sugeridas em seu código, contudo, o hibernate ainda não conseguiu gerar a DDL no banco.

Estou usando o MySQL 4.1

O que pode ser?

:wink:

D

2006-07-24 13:01:09,092 DEBUG tool.hbm2ddl.SchemaExport -> import file not found: /import.sql

Será que é isso? :shock:

:wink:

T

Blz,

Cara, estou utilizando o mysql 1.4 também, e funciona normalmente.

Posta o código para a gente dar uma olhada.

Falo.

Tubarão - MG

T

Cara lembrei de uma coisa;

Você, já criou a database no mysql.

Exemplo:

CREATE DATABASE jteste

E depois você tenta rodar!!!

Falooo

T

E outra coisa vá no seu hibernate.properties e habilite a sequinte linha também:

hibernate.dialect org.hibernate.dialect.MySQLDialect

Faloo

D

Caro amigo.

No primeiro tópico, se encontra meu código:
Contudo aqui esta o hibernate.properties:

hibernate.dialect = org.hibernate.dialect.MySQLDialect
 hibernate.connection.driver_class = com.mysql.jdbc.Driver
 hibernate.connection.url = jdbc:mysql://localhost/jteste
 hibernate.connection.username = root
 hibernate.connection.password =

O DataBase já está criado, inclusive, inseri manualmente a tabela produto, para testar as sessões e funcionou normal. Somente não está criando a tabela.

Tentei o mesmo com o Firebird, e executa, contudo, não cria a tabela.
Para o firebird usei o hibernate.properties:

hibernate.dialect = org.hibernate.dialect.InterbaseDialect
hibernate.connection.driver_class = org.firebirdsql.jdbc.FBDriver
hibernate.connection.url = jdbc:firebirdsql:localhost:c:/java/hbb/amigos.fdb?sql_dialect=3
hibernate.connection.username = SYSDBA
hibernate.connection.password = masterkey

Achei esta dúvida em outros posts, mas ainda não obtive uma solução.
:cry:

T

tem uma propriedade que chama hbm2ddl e vc deve setar como update para ele gerar as tabelas e as constraints

D

O hibernate.properties ficou assim agora:

Roda tudo normal, mas não aparece a tabela no banco.
Ja tentei com MySQL, Firebird.

:wink:

T

hibernate.hbm2ddl.auto=update

vai validar e atualizar o esquema se necessario

create vai criar do zero (vai apagar dados jah existentes)
create-drop vai criar do zero e vai apagar quando a aplicacao fechar (acho)
validade soh vai validar

D

Ola


hibernate.hbm2ddl.auto=update

vai validar e atualizar o esquema se necessario

create vai criar do zero (vai apagar dados jah existentes)
create-drop vai criar do zero e vai apagar quando a aplicacao fechar (acho)
validade soh vai validar


Caro takeshi10 , fiz o acerto no arquivo de configurações (hibernate.properties).

Gostaria de agradecer a todos a atenção desempenhada. E ainda preciso mais :lol:

Encontrei o erro:

Não está gerando o arquivo /import.sql.

Fiz um teste criando um arquivo “import.sql” manualmente, rodei a aplicação e funcionou. Pelo que entendi, o tool.hbm2ddl.SchemaExport cria o arquivo SQL e depois envia ao SGBD.

Alguém tem alguma sugestão para solucionar isto?

:wink:

P

use a classe SchemaExport, passando Configuration como argumento, e depois chame o metodo (create ?) passando true true

D

Por favor!!! Se puder analisar o código. Segue anexos:

D

Ainda não desisti :lol:

Alguém tem um exemplo, e poderia me enviar.
Assim eu iria testar e comparar com minhas classes.

Agradeço a ajuda de todos.

:wink:

D

Caros Amigos!

Consegui resolver este problema. A quem interessar segue solução:

1º Erro: Estava importando a classe Entity do pacote org.hibernate.annotations, o correto é importar da javax.persistence. Lembrando que estou usando o J2SE.

2º Erro: A versão do Hibernate o qual estava usando era a 3.1, o qual é incompatível com o Hibernate Annotations 3.2. Para esta versão do Annotations usar somente a versão 3.2 CR2 do Hibernate, ou superior.

Bom amigos, obrigado a todos pelo apoio. Espero, que esta thread, possa ajudar muitos à não cometer os mesmos erros. :lol:

Irei seguir agora no treinamento. Abraços!

:wink:

K

My Brother Parabens !

Eu estou comecando e estava me matando, depois de importar o Entity do local correto funcionou perfeitamente !

T

Cara vá na sua classe Produto.java e altere a seguinte linha:

import org.hibernate.annotations.Entity;

por esta linha:

import javax.persistence.Entity;

provavelmente irá funcionar…

Abraço

R

Eu gerei uma tabela de teste
não tive problemas em gerar,
entretanto minhas classes são

Cliente{id,contato}

Contato{id, bla bla bla}

1 Cliente recebe um ou vários contatos num List, as tabelas foram geradas, foi criado a tabela Cliente_Contato, na hora de fazer a inserção, insere normalmente o Cliente, e os contatos adicionado na lista, de contatos do usuário, salvam no banco, mas não insere nenhuma referencia na tabela Cliente_Contato.

Segue Classes:

@Entity
public class Cliente {
	@Id
	@GeneratedValue
	private Long id;
	private String nome;
	private String sobrenome;
	private String email;
	private String senha;
	private String cpfCnpj;
	private String rgIe;

	@OneToMany(cascade = CascadeType.ALL)
	private List<Contato> contatos;

	
	public List<Contato> getContatos() {
		return contatos;
	}
	public void setContatos(List<Contato> contatos) {
		this.contatos = contatos;
	}

}
@Entity
public class Contato {
	@Id @GeneratedValue
	private Long id;
	private String endereco;
	private String numero;
	private String cep;
	private String bairro;
	private String cidade;
	private String uf;
	private String telefone;
	private String celular;
	
}
Contato c1 = new Contato();
		c1.setEndereco("r. aquidaban");
		c1.setUf("SP");
		
		Contato c2 = new Contato();
		c2.setUf("SP");
		
		
		
		List<Contato> contatos = new ArrayList<Contato>();
		contatos.add(c1);
		contatos.add(c2);
		
		
		Cliente cl = new Cliente();
		cl.setNome("Roberto");
		cl.setContatos(contatos);
		
		
		
		Session session = new HibernateUtil().getSession();
		session.save(cl);
J

Paulo Silveira:
use a classe SchemaExport, passando Configuration como argumento, e depois chame o metodo (create ?) passando true true

É eu também recomendaria o SchemaExport, é mais garantia

https://www.hibernate.org/291.html

att,

R

Bom, eu usei para gerar as classes
new SchemaExport(cfg).create(true, true);

A

Estou com o mesmo problema, o servidor tomcat roda mas não gera as tabelas. Usando o mySql 5.1
ja tentei com Create e Update mas ate o momento nada.

Criado 24 de julho de 2006
Ultima resposta 1 de ago. de 2013
Respostas 21
Participantes 9