Erro ao executar SchemaExport no hibernate 3.5 - Exercicio Caelum

1 resposta
R

Senhores, estou com um grave problema ao configurar o hibernate nun projeto java desde esta manhã, é o exercicio 13.6 do curso FJ21.
Minha versão do MySQL é a 6.0
Meu Eclipse é a 3.3.2

A Exception a seguir só ocorre quando o parametro se.create(boolean, boolean); é falso, ou seja, somente quando eu EXECUTO a sql gerada, quando deixo ele como false, ele me mostra a query e não gera exception. Obrigado senhores, desde já!

Aqui vai o log:
20:38:10  INFO [Version             ] Hibernate Annotations 3.5.0-Final
20:38:10  INFO [Environment         ] Hibernate 3.5.0-Final
20:38:10  INFO [Environment         ] loaded properties from resource hibernate.properties: {hibernate.connection.username=root, hibernate.connection.password=****, hiberntae.connection.url=jdbc:mysql://localhost/fj21, hibernate.dialect=org.hibernate.dialect.MySQLDialect, hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.connection.driver_class=com.mysql.jdbc.Driver, hibernate.format_sql=true}
20:38:10  INFO [Environment         ] Bytecode provider name : javassist
20:38:10  INFO [Environment         ] using JDK 1.4 java.sql.Timestamp handling
20:38:10  INFO [Version             ] Hibernate Commons Annotations 3.2.0.Final
20:38:10  INFO [Dialect             ] Using dialect: org.hibernate.dialect.MySQLDialect
20:38:10  INFO [AnnotationBinder    ] Binding entity from annotated class: br.com.caelum.hibernate.Produto
20:38:10  INFO [EntityBinder        ] Bind entity br.com.caelum.hibernate.Produto on table Produto
20:38:10  INFO [AnnotationConfiguration] Hibernate Validator not found: ignoring
20:38:11  INFO [SchemaExport        ] Running hbm2ddl schema export
20:38:11  INFO [SchemaExport        ] exporting generated schema to database
20:38:11  WARN [UserSuppliedConnectionProvider] No connection properties specified - the user must supply JDBC connections
20:38:11 ERROR [SchemaExport        ] schema export unsuccessful
java.lang.UnsupportedOperationException: The user must supply a JDBC connection
	at org.hibernate.connection.UserSuppliedConnectionProvider.getConnection(UserSuppliedConnectionProvider.java:54)
	at org.hibernate.tool.hbm2ddl.ManagedProviderConnectionHelper.prepare(ManagedProviderConnectionHelper.java:52)
	at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:252)
	at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:211)
	at br.com.caelum.hibernate.GeraTabelas.main(GeraTabelas.java:11)

As dependencias que estou utilizando até agora são:

[list]antlr-2.7.6.jar[/list]
[list]c3p0-0.9.1.jar[/list]
[list]commons-collections-3.1.jar[/list]
[list]dom4j-1.6.1.jar[/list]
[list]ehcache-1.5.0.jar[/list]
[list]hibernate3.jar[/list]
[list]hibernate-jpa-2.0-api-1.0.0.Final.jar[/list]
[list]hibernate-jpamodelgen-1.0.0.Final.jar[/list]
[list]javassist-3.9.0.GA.jar[/list]

Meu hibernate properties é:

hibernate.properties
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hiberntae.connection.url = jdbc:mysql://localhost/fj21
hibernate.connection.username = root
hibernate.connection.password = senha
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.dialect = org.hibernate.dialect.MySQLDialect
jta-1.1.jar
log4j-1.2.15.jar
mysql-connector-java-5.0.7-bin.jar
slf4j-log4j12-1.5.8.jar

Log4j properties:
log4j.properties

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss} %5p [%-20c{1}] %m%n

log4j.rootLogger=warn, stdout
log4j.logger.org.hibernate=info

Minha classe modelo (posso dizer q é a que tem os beans né? gets e sets)

Produto.java

package br.com.caelum.hibernate;

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 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;
	}
}

Classe com método main que executa as ações

GeraTabelas.java
package br.com.caelum.hibernate;

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);
		}
}

Eu imaginei que estava dando erro com o driver jdbc do mysql, então usei a classe factory de conexões e testei, conectou normalmente.

ConnectionFactory.java
package br.com.caelum.hibernate;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {
	public Connection getConnection() {
		System.out.println("Conectando ao banco");
		try {
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Connection con = DriverManager.getConnection(
					"jdbc:mysql://localhost/fj21", "root",
					"senha");
			System.out.println("Conectado");
			return con;

		} catch (SQLException e) {
			System.out.println("Erro no getConnection");
			throw new RuntimeException(e);
		}
	}
}

Testa a conexão:

TestaConnectionFactory.java
package br.com.caelum.hibernate;

import java.sql.Connection;
import java.sql.SQLException;

public class TestaConnectionFactory {
	public static void main(String[] args) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		Connection connection = new ConnectionFactory().getConnection();
		connection.close();
	}
}

1 Resposta

R

Senhores já consegui :-) este tópico colaborou totalmente http://www.guj.com.br/java/209971-hibernate-com-hibernateproperties
Eu estava a utilizar o arquivo hibernate.properties pois não conseguia fazer funcionar o hibernate.cfg.xml , através do tópico já mencionado descobri que só precisava chamar o método: cfg.configure(); sendo que ele é do tipo AnnotationConfiguration., bem ficou assim o meu GeraTabelas.java e o meu hibernate.cfg.xml:

[i]GeraTabelas.java

package br.com.caelum.hibernate;

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.configure();
		cfg.addAnnotatedClass(Produto.class);
		SchemaExport se = new SchemaExport(cfg);
		se.create(true, true);
		}
}

E o meu hibernate.cfg.xml , que está na pasta source do meu projeto, ficou assim:

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//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/fj21</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">reload</property>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<mapping class="br.com.caelum.hibernate.Produto"/>
		<mapping class="br.com.caelum.hibernate.GeraTabelas"/>
	
	</session-factory>
</hibernate-configuration>

Caso os moderadores acharem necessário devido a grande repetição de tópicos com este assunto, fiquem à vontade para excluir, se não, de qualquer forma fica registrado aqui a forma de resolução para especificamente este problema. Deus abençõe vocês.

Criado 3 de novembro de 2011
Ultima resposta 3 de nov. de 2011
Respostas 1
Participantes 1