Problema básico Hibernate

7 respostas
P

Opa tudo bem??

Então estou com o seguinte probleminha aqui com o hibernate

Eu até consigo criar as tabelas e tudo mais,mas o problema aparece mesmo quando vou inserir os dados nas tabelas.

Vejam só:

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

@Entity
public class Produto {

	@Id
	@GeneratedValue
	private Long id;
	
	private String nome;
	private String descricao;
	private double preco;
	
	
	public Produto() {
		
	}
	
	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 getDescricao() {
		return descricao;
	}
	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}
	public double getPreco() {
		return preco;
	}
	public void setPreco(double preco) {
		this.preco = preco;
	}
	
	
	
	
}
Essa eh minha classe modelo.
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class GeraTabelas {
	
	 public static void main(String[] args) {
		
		AnnotationConfiguration cfg = new AnnotationConfiguration();
		cfg.addAnnotatedClass(Produto.class);
		
		SchemaExport se = new SchemaExport(cfg);
		se.create(true, true);
		
	}

}
Até aqui beleza ele gera as tabelas numa boa!
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;


public class AdicionaProdutos {

	public static void main(String[] args) {
		
		Produto p = new Produto();
		p.setNome("Nome aqui");
		p.setDescricao("descrição aqui");
		p.setPreco(100.50);
		
		AnnotationConfiguration cfg = new AnnotationConfiguration();
		cfg.addAnnotatedClass(Produto.class);
		
		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();
		
		session.beginTransaction();
		session.save(p);
		session.getTransaction().commit();
		
		System.out.println("ID do produto: " + p.getId());
		session.close();
		
 	     }
	
}

Ai depois disso coloco para rodar a classe AdicionaProduto e da o seguinte erro:

[color=darkred]18:52:48 WARN [JDBCExceptionReporter] SQL Error: 1146, SQLState: 42S02
18:52:48 ERROR [JDBCExceptionReporter] Table 'teste.produto' doesn't exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [br.com.leonardo.hibernate.Produto]

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'teste.produto' doesn't exist[/color]

Me ajudem por favor!
Valeu galera!!

7 Respostas

Victor_Neves

o HIbernate está procurando a tabela Produto dentro da database ‘teste’.
se essa database não existe então não há o que achar…

posta ai o seu hibernate.cfg.xml

P

Ai está…

hibernate.dialect = org.hibernate.dialect.MySQLInnoDBDialect
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost/teste
hibernate.connection.username = root
hibernate.connection.password = 
hibernate.show_sql = true
hibernate.format_sql = true
Victor_Neves

e ele cria a tabela? voce ve a tabela la no banco?

P

Não,ele não cria nenhuma tabela,agora que percebi na hora de rodar a classe para gerar as tabelas ele apresenta o seguinte erro:

00:23:05 ERROR [SchemaExport] Unsuccessful: create table Produto (id bigint not null auto_increment, descricao varchar(255), nome varchar(255), preco double precision not null, primary key (id)) type=InnoDB

00:23:05 ERROR [SchemaExport] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘type=InnoDB’ at line 1

drsmachado

Não use o schema.export(true, true), prefira configurar, no hibernate.properties, a propriedade

hibernate.hbm2ddl.auto = update

Isso faz com que a tabela seja verificada, se não existir, será criada, se existir e a classe foi alterada, a tabela é alterada, senão, continua da mesma forma.

P

Ainda não resolveu o problema,fiz o que vc falou e apaguei SchemaExport,ai depois de ter apagado ele foi impresso no console o seguinte:

13:59:15 INFO [Version] Hibernate Annotations 3.4.0.GA
13:59:15 INFO [Environment] Hibernate 3.3.2.GA
13:59:15 INFO [Environment] loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=com.mysql.jdbc.Driver, hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect, hibernate.format_sql=true, hibernate.connection.username=root, hibernate.hbm2ddl.auto=update, hibernate.connection.url=jdbc:mysql://localhost/teste, hibernate.bytecode.use_reflection_optimizer=false, hibernate.show_sql=true, hibernate.connection.password=****}
13:59:15 INFO [Environment] Bytecode provider name : javassist
13:59:15 INFO [Environment] using JDK 1.4 java.sql.Timestamp handling
13:59:15 INFO [Version] Hibernate Commons Annotations 3.1.0.GA

Ele não me mostrou q as tabelas foram criadas,chequei no bd e nada das tabelas.

Vyccus
00:23:05 ERROR [SchemaExport] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'type=InnoDB' at line 1

A sintax da sql gerada está com problema. Eu não manjo de mysql, então não posso ajudar quanto a isso.

Criado 11 de junho de 2012
Ultima resposta 14 de jun. de 2012
Respostas 7
Participantes 4