[Dúvida] - Hibernate, exceção

13 respostas
litium

Boa noite pessoa do GUJ!

Sumi por um tempo aqui do fórum. Passei bom tempo estudando outros assuntos do Java. Agora, comprei um livro de Hibernate ("Java persistence com hibernate") e quis começar do novo meus estudos. Sem mais apostilas incompletas!

A minhas dúvida está em manipulação de dados em uma tabela. Algo estupidamente simples (para mim, não tá sendo), inserir uma pessoa na tabela pessoa no banco de dados. A tabela só tem dois campos, id e nome da pessoa. Acontece que quando inicio o meu método main, aparece as informações do log e tal, e, depois, algo de errado acontece. O mapeamento de minha tabela foi feita usando XML e não anotações. Não estou sabendo como consertar isso no momento. Se alguém puder me dar uma luz:

18/12/2010 20:54:51 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.1.3
18/12/2010 20:54:51 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
18/12/2010 20:54:51 org.hibernate.cfg.Environment <clinit>
INFO: using CGLIB reflection optimizer
18/12/2010 20:54:51 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
18/12/2010 20:54:51 org.hibernate.cfg.Configuration configure
INFO: configuring from resource: xmls/configurador/hibernate.cfg.xml
18/12/2010 20:54:51 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: xmls/configurador/hibernate.cfg.xml
18/12/2010 20:54:52 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource: xmls/pojos/Pessoa.hbm.xml
18/12/2010 20:54:52 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: pojos.Pessoa -> pessoa
18/12/2010 20:54:52 org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
18/12/2010 20:54:52 org.hibernate.connection.C3P0ConnectionProvider configure
INFO: C3P0 using driver: org.hsqldb.jdbcDriver at URL: jdbc:hsqldb:hsql://127.0.0.1:3307/estudo_hibernate
18/12/2010 20:54:52 org.hibernate.connection.C3P0ConnectionProvider configure
INFO: Connection properties: {user=hibernate, password=****}
18/12/2010 20:54:52 org.hibernate.connection.C3P0ConnectionProvider configure
INFO: autocommit mode: false
18/12/2010 20:54:52 com.mchange.v2.log.MLog <clinit>
INFO: MLog clients using java 1.4+ standard logging.
18/12/2010 20:54:52 com.mchange.v2.c3p0.C3P0Registry banner
INFO: Initializing c3p0-0.9.0 [built 11-July-2005 00:43:29 -0400; debug? true; trace: 10]
18/12/2010 20:54:52 com.mchange.v2.c3p0.PoolBackedDataSource getPoolManager
INFO: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@1125127 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@72ffb [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 72ffb, idleConnectionTestPeriod -> 3000, initialPoolSize -> 5, maxIdleTime -> 300, maxPoolSize -> 20, maxStatements -> 50, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@3901c6 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 3901c6, jdbcUrl -> jdbc:hsqldb:hsql://127.0.0.1:3307/estudo_hibernate, properties -> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 300, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, usesTraditionalReflectiveProxies -> false ], factoryClassLocation -> null, identityToken -> 1125127, numHelperThreads -> 3 ]
18/12/2010 20:55:51 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run
AVISO: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@15212bc -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30).
18/12/2010 20:55:51 org.hibernate.cfg.SettingsFactory buildSettings
AVISO: Could not obtain connection metadata
java.sql.SQLException: Connections could not be acquired from the underlying database!
	at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:104)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:236)
	at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:94)
	at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:35)
	at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:72)
	at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1881)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1174)
	at utilidades.HibernateUtil.<clinit>(HibernateUtil.java:14)
	at testes.PessoaTeste.main(PessoaTeste.java:12)
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
	at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:970)
	at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:208)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:232)
	... 7 more
18/12/2010 20:55:51 org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.HSQLDialect
18/12/2010 20:55:52 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
18/12/2010 20:55:52 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: disabled
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): disabled
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
18/12/2010 20:55:52 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
18/12/2010 20:55:52 org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.EhCacheProvider
java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException
	at java.lang.Class.getDeclaredConstructors0(Native Method)
	at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
	at java.lang.Class.getConstructor0(Unknown Source)
	at java.lang.Class.newInstance0(Unknown Source)
	at java.lang.Class.newInstance(Unknown Source)
	at org.hibernate.cfg.SettingsFactory.createCacheProvider(SettingsFactory.java:327)
	at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:219)
	at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1881)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1174)
	at utilidades.HibernateUtil.<clinit>(HibernateUtil.java:14)
	at testes.PessoaTeste.main(PessoaTeste.java:12)
Caused by: java.lang.ClassNotFoundException: net.sf.ehcache.CacheException
	at java.net.URLClassLoader$1.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	... 11 more
Exception in thread "main" java.lang.NullPointerException
	at testes.PessoaTeste.main(PessoaTeste.java:12)

Gggrrrrr!!! :x

Esse maldito está me matando "Could not obtain connection metadata". Não sei o que significa.

Olha só o meu arquivo hibernate.cfg.xml:

<?xml version="1.0"?>

<!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		
		<property name = "hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
		<property name = "hibernate.connection.url">jdbc:hsqldb:hsql://127.0.0.1:3307/estudo_hibernate</property>
		<property name = "hibernate.connection.username">hibernate</property>
		<property name = "hibernate.connection.password">hibernate</property>
		<property name = "hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
		
		<!-- Utiliza c3p0 para gerenciar pool de conexões com banco -->
		<property name = "hibernate.c3p0.min_size">5</property>
		<property name = "hibernate.c3p0.max_size">20</property>
		<property name = "hibernate.c3p0.timeout">300</property>
		<property name = "hibernate.c3p0.max_statements">50</property>
		<property name = "hibernate.c3p0.idle_test_period">3000</property>
		
		<property name = "show_sql">true</property>
		<property name = "format_sql">true</property>
		
		<mapping resource = "xmls/pojos/Pessoa.hbm.xml"/>
	
	</session-factory>
</hibernate-configuration>

No tópico tá aparecendo que a URL está assim "estudo hibernate". Mas na verdade, está sublinhado assim: "estudo_hibernate".

E meus jars do Hibernate são esses:

astlr-2.7.5H3.jar
asm-attrs.jar
asm.jar
c3p0-0.9.0.jar
cglib-2.1.jar
commons-collections-3.2.jar
commons-logging.jar
dom4j-1.6.jar
hibernate3.jar
hsqldb-1.7.2.2.jar
jta.jar

Até com a ferramenta do próprio Hibernate, a HSQL Database Manager, eu não consigo me conectar ao banco de dados. Quando vou me conectar, aparece um "java.sql.SQLException: socket creation error". Ai ai... Ficarei grato se alguém pelo menos me der uma dica do que diabos pode ser isso. Eu falei com meu professor pelo msn uma vez, e o infeliz ainda falou: "Calma, daqui pra frente ainda piora!". :shock:

Abraços GUJ!

13 Respostas

romarcio

O problema parece ser esse:

Exception in thread "main" java.lang.NullPointerException  
    at testes.PessoaTeste.main(PessoaTeste.java:12)

NullPointer na linha 12 do método main na classe PessoaTeste.

Verifica isso, se não conseguir resolver posta essa classe.

litium
romarcio:
O problema parece ser esse:
Exception in thread "main" java.lang.NullPointerException  
    at testes.PessoaTeste.main(PessoaTeste.java:12)

NullPointer na linha 12 do método main na classe PessoaTeste.

Verifica isso, se não conseguir resolver posta essa classe.

romarcio, a linha 12, tem isso:

Session sessao = HibernateUtil.getSessionFactory().openSession();

A classe PessoaTeste só cria uma pessoa e a adiciona na tabela:

import org.hibernate.*;
import pojos.Pessoa;
import utilidades.HibernateUtil;

public class PessoaTeste
{
	public static void main(String[] args)
	{
		// Pega uma conexão do pool de conexões com banco
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = sessao.beginTransaction();
		
		Pessoa pessoa = new Pessoa();
		pessoa.setNome("Testando este programa");
		
		sessao.save(pessoa);
		
		// Termina transação e devolve conexão ao pool de conexões com o banco
		transaction.commit();
		sessao.close();
		
		// Encerra pool de conexões com banco
		HibernateUtil.encerrarConexao();
	}
}

Andei falando com uns por aí. Me disseram que é problema no próprio HSQLDB. Me disseram para usar MySQL, mas seria bacana poder aprender uma coisa nova e também, seguir os exemplo do livro, os quais estão todos em HSQLDB.

Se alguém souber de alguma coisa, aceito qualquer dica!

Abraços GUJ!

romarcio

O problema está sendo exibido na linha 84 do log postado: java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException
Ou seja, está faltando essa classe para o hibernate funcionar ok.

Vc deve adicionar esse jar: ehcache-xxx.jar
Acho que a última versão é essa: ehcache-1.5.0.jar
Procura e adiciona no seu projeto.

litium

E aí romarcio!

Cara, eu achei só o ehcache-1.0 no findjar. Coloquei ele no meu BuildPath e rodei o PessoaTeste. Parece… ter resolvido o problema. Mas surgiu outro:

(INFOs comuns de log) <-- ...

AVISO: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@37fb1e -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30).
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
AVISO: Could not obtain connection metadata
java.sql.SQLException: Connections could not be acquired from the underlying database!
	at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:104)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:236)
	at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:94)
	at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:35)
	at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:72)
	at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1881)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1174)
	at utilidades.HibernateUtil.<clinit>(HibernateUtil.java:14)
	at testes.PessoaTeste.main(PessoaTeste.java:12)
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
	at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:970)
	at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:208)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:232)
	... 7 more
25/12/2010 01:26:49 org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.HSQLDialect
25/12/2010 01:26:49 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
25/12/2010 01:26:49 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
25/12/2010 01:26:49 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.EhCacheProvider
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
25/12/2010 01:26:49 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
25/12/2010 01:26:49 org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
25/12/2010 01:26:49 net.sf.ehcache.config.Configurator configure
AVISO: No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Documents%20and%20Settings/Administrador/Meus%20documentos/Projetos%20Eclipse/Hibernate%20Livro/Libs/ehcache-1.0.jar!/ehcache-failsafe.xml
25/12/2010 01:26:49 org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
25/12/2010 01:26:50 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run
AVISO: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@f42ad0 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30).
25/12/2010 01:26:50 org.hibernate.util.JDBCExceptionReporter logExceptions
AVISO: SQL Error: 0, SQLState: null
25/12/2010 01:26:50 org.hibernate.util.JDBCExceptionReporter logExceptions
GRAVE: Connections could not be acquired from the underlying database!
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection
	at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
	at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
	at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
	at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:129)
	at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
	at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1290)
	at testes.PessoaTeste.main(PessoaTeste.java:13)
Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
	at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:104)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:236)
	at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:94)
	at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:35)
	at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
	... 5 more
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
	at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:970)
	at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:208)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:232)
	... 8 more

Acredito que tem algo de errado com o HSQLDB. Tá aparecendo direto que não houve nenhuma conexão com o banco de daos. Várias tentativas e nada.

O que recomenda que eu faça agora?

Alguém também sugere alguma coisa?

Aguardo respostas.

Abraços GUJ!

romarcio

Você está usando o gerenciador do HSQLDB?

Se sim, vc já criou o banco de dados por ele?

Ou vc está usando o HSQLDB no mode standalone?

litium

romarcio:
Você está usando o gerenciador do HSQLDB?

Se sim, vc já criou o banco de dados por ele?

Ou vc está usando o HSQLDB no mode standalone?

Que burrice a minha! Pode crer… Meu deus… Tava sem noção do que fazer. Como eu faço para usar comandos DDL no HSQLDB Manager?

romarcio

Já leu esse tutorial do guj?
http://www.guj.com.br/content/articles/hsqldb/hsqldb_guj.pdf

Depois de criar o banco, vc pode usar o próprio hibernate para criar as tabelas.

Use essa classe:
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class GeraBanco {
	public static void main(String[] args) {
		Configuration cfg = new Configuration();
                cfg.configure();
		new SchemaExport(cfg).create(true, true);
	}
}

Ela cria as tabelas através de seu mapeamento.

No seu aquivo hibernate.cfg.xml, coloque essa linha:
&lt;property name="hbm2ddl.auto"&gt;create&lt;/property&gt;
Se preferir criar as tabelas na mão, segue um exemplo:
Criando Tabelas:
ATIVIDADE: Para isso basta executar o seguinte script SQL.
&gt; CREATE TABLE PERSON (
cd_person INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL,
ds_name VARCHAR(64) NOT NULL,
CONSTRAINT pk_person PRIMARY KEY (cd_person)
);
&gt; CREATE TABLE CAR (
cd_car INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL,
cd_person INTEGER NOT NULL,
ds_name VARCHAR(64) NOT NULL,
CONSTRAINT pk_car PRIMARY KEY (cd_car)
);
&gt; ALTER TABLE CAR ADD CONSTRAINT
fk_person_car FOREIGN KEY (cd_person)
REFERENCES PERSON (cd_person) ON UPDATE CASCADE ON DELETE CASCADE;
litium

Calminha...

Você está me dando 3 maneiras distintas de se criar tabelas, não é? Eu posso tanto fazer de um jeito, como de outro, certo?

Só que esse terceiro jeito aí:

Criando Tabelas:  
ATIVIDADE: Para isso basta executar o seguinte script SQL.  
> CREATE TABLE PERSON (  
cd_person INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL,  
ds_name VARCHAR(64) NOT NULL,  
CONSTRAINT pk_person PRIMARY KEY (cd_person)  
);  
> CREATE TABLE CAR (  
cd_car INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL,  
cd_person INTEGER NOT NULL,  
ds_name VARCHAR(64) NOT NULL,  
CONSTRAINT pk_car PRIMARY KEY (cd_car)  
);  
> ALTER TABLE CAR ADD CONSTRAINT  
fk_person_car FOREIGN KEY (cd_person)  
REFERENCES PERSON (cd_person) ON UPDATE CASCADE ON DELETE CASCADE;

Eu devo colocar isso onde?

Se o que eu entendi estiver errado, por favor me avise. Enquanto isso, vou imediatamente ler o tutorial do GUJ. Se der certo de algum jeito que eu fiz, pretendo postar aqui de novo, assim, darei mais conteúdo ao tópico.

Farei testes, depois retorno aqui.

Obrigado romarcio!

OBS: Moderadores, queria pedir por gentileza se seria possível colocar o título do tópico algo assim: [Dúvida] - Hibernate, configurando e utilizando HSQLDB. O tópico ganhou bastante conteúdo. Se puderem, iria até ajudar outros. Obrigado.

Abraços GUJ!

romarcio

O 3° vc utiliza no gerenciador do HSQLDB que vc deve ter instalado no PC.

Qualquer dúvida sobre a criação do banco ou acesso ao gerenciador, vc pode tirar no tutorial do guj do qual te passei o link.

litium

E aí romarcio.

Eu tenho um pacote com as duas versões do programa, AWT e SWING. Aí eu rodo o SWING no eclipse. Vi pelo link do pdf que você me mandou que o HSQLDB tem ferramentas e alguns modos de peristir dados, memória, temporário (vivo apenas durante a utilização do banco), servidor web e standalone.

Existem algumas coisas que estou com dúvida.

1 - Uma delas é: Eu consegui criar uma tabela pelo modo "in-memory". No pdf diz isso aqui:

"O HSQLDB permite que possamos executar o SGBD de forma que os dados sejam mantidos em memória. Essa é uma técnica que mantém todo o conjunto de dados de uma tabela na memória do computador, permitindo uma melhor performance do SGBD. Esse modo de execução deverá ser utilizado somente em algumas situações especiais. A seguir, veremos o exemplo de conexão utlizando o protocolo de memória."

Quando ele diz na "memória do computador", os dados não são persistidos em arquivo algum, certo? Qual a vantagem de se persistir dados assim?

2 - Outra coisa que fiquei com dúvida, foi que eu tentei criar uma tabela assim:

CREATE MEMORY TABLE pessoa
(  
id_pessoa INTEGER NOT NULL AUTO_INCREMENT,  
nome_pessoa VARCHAR(64),  
PRIMARY KEY (id_pessoa)  
);

E o HSQLDB Manager Swing me deu este erro:

Unexpected token: AUTO_INCREMENT in statement [CREATE MEMORY TABLE pessoa ( id_pessoa INTEGER NOT NULL AUTO_INCREMENT] / Error Code: -1/State:37000

As instruções SQL DDL aqui são diferentes? Como funciona isso?

3 - Como posso gerenciar/criar um banco de dados com um nome meu? Falo isso pois quando vou usar o HSQLDB Manager Swing em modo "in-memory", eu faço as coisas como se um banco de dados já estivesse criado. E como mudo/crio/gerencio os usuários para conexão com o banco?

4 - (Eu sei que tem muita dúvida, mas fiz várias coisas que criaram dúvidas) Tentei usar o Hibernate (de novo) para fazer conexão com HSQLDB, mas uma nova exceção foi lançada:

27/12/2010 15:55:41 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.1.3
27/12/2010 15:55:41 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
27/12/2010 15:55:41 org.hibernate.cfg.Environment <clinit>
INFO: using CGLIB reflection optimizer
27/12/2010 15:55:42 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
27/12/2010 15:55:42 org.hibernate.cfg.Configuration configure
INFO: configuring from resource: xmls/configurador/hibernate.cfg.xml
27/12/2010 15:55:42 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: xmls/configurador/hibernate.cfg.xml
27/12/2010 15:55:42 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource: xmls/pojos/Pessoa.hbm.xml
27/12/2010 15:55:42 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: pojos.Pessoa -> pessoa
27/12/2010 15:55:42 org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
27/12/2010 15:55:42 org.hibernate.connection.C3P0ConnectionProvider configure
INFO: C3P0 using driver: org.hsqldb.jdbcDriver at URL: jdbc:hsqldb:hsql://localhost
27/12/2010 15:55:42 org.hibernate.connection.C3P0ConnectionProvider configure
INFO: Connection properties: {user=sa}
27/12/2010 15:55:42 org.hibernate.connection.C3P0ConnectionProvider configure
INFO: autocommit mode: false
27/12/2010 15:55:42 com.mchange.v2.log.MLog <clinit>
INFO: MLog clients using java 1.4+ standard logging.
27/12/2010 15:55:42 com.mchange.v2.c3p0.C3P0Registry banner
INFO: Initializing c3p0-0.9.0 [built 11-July-2005 00:43:29 -0400; debug? true; trace: 10]
27/12/2010 15:55:42 com.mchange.v2.c3p0.PoolBackedDataSource getPoolManager
INFO: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@af8358 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@a6aeed [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> a6aeed, idleConnectionTestPeriod -> 3000, initialPoolSize -> 5, maxIdleTime -> 300, maxPoolSize -> 20, maxStatements -> 50, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@66e815 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 66e815, jdbcUrl -> jdbc:hsqldb:hsql://localhost, properties -> {user=******} ], preferredTestQuery -> null, propertyCycle -> 300, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, usesTraditionalReflectiveProxies -> false ], factoryClassLocation -> null, identityToken -> af8358, numHelperThreads -> 3 ]
27/12/2010 15:56:42 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run
AVISO: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@1a9334 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30).
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
AVISO: Could not obtain connection metadata
java.sql.SQLException: Connections could not be acquired from the underlying database!
	at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:104)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:236)
	at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:94)
	at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:35)
	at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:72)
	at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1881)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1174)
	at utilidades.HibernateUtil.<clinit>(HibernateUtil.java:14)
	at testes.PessoaTeste.main(PessoaTeste.java:12)
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
	at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:970)
	at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:208)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:232)
	... 7 more
27/12/2010 15:56:42 org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.HSQLDialect
27/12/2010 15:56:42 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
27/12/2010 15:56:42 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
27/12/2010 15:56:42 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.EhCacheProvider
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
27/12/2010 15:56:42 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
27/12/2010 15:56:42 org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
27/12/2010 15:56:42 net.sf.ehcache.config.Configurator configure
AVISO: No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Documents%20and%20Settings/Administrador/Meus%20documentos/Projetos%20Eclipse/Hibernate%20Livro/Libs/ehcache-1.0.jar!/ehcache-failsafe.xml
27/12/2010 15:56:43 org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
27/12/2010 15:56:43 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: Running hbm2ddl schema export
27/12/2010 15:56:43 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: exporting generated schema to database
27/12/2010 15:56:43 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run
AVISO: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@c44b88 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30).
27/12/2010 15:56:43 org.hibernate.tool.hbm2ddl.SchemaExport execute
GRAVE: schema export unsuccessful
java.sql.SQLException: Connections could not be acquired from the underlying database!
	at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:104)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:236)
	at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:94)
	at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:35)
	at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:27)
	at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:178)
	at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:131)
	at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:295)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1176)
	at utilidades.HibernateUtil.<clinit>(HibernateUtil.java:14)
	at testes.PessoaTeste.main(PessoaTeste.java:12)
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
	at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:970)
	at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:208)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:232)
	... 9 more
27/12/2010 15:57:43 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run
AVISO: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@18235ed -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30).
27/12/2010 15:57:43 org.hibernate.util.JDBCExceptionReporter logExceptions
AVISO: SQL Error: 0, SQLState: null
27/12/2010 15:57:43 org.hibernate.util.JDBCExceptionReporter logExceptions
GRAVE: Connections could not be acquired from the underlying database!
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection
	at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
	at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
	at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
	at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:129)
	at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
	at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1290)
	at testes.PessoaTeste.main(PessoaTeste.java:13)
Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
	at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:104)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:236)
	at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:94)
	at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:35)
	at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
	... 5 more
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
	at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:970)
	at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:208)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:232)
	... 8 more

Meu hibernate.cfg.xml foi alterado com estas coisas:

<property name = "hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
		<property name = "hibernate.connection.url">jdbc:hsqldb:hsql://localhost</property>
		<property name = "hibernate.connection.username">sa</property>
		<property name = "hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>

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

Não sei o que estou fazendo de errado ainda. O pdf ensina a conectar com o HSQL SEM O USO do Hibernate nos exemplos dele. Posso tá falando besteira em dizer isso, mas digo que ele não usa o Hibernate nos exemplo pois ele faz uso da classe DriverManager e da Interface Connection.

A minha intenção é utilizar o Hibernate para gerenciar o banco de dados HSQLDB e também, depois, fazer isso de forma standalone persistindo dados no desktop (em arquivos). Mas... baaah... Tá difícil!

Aguardo ajuda!

Abraços GUJ!

romarcio

Vamos criar um banco do tipo standalone:

Faz assim:
public class GeraBanco {
	public static void main(String[] args) {
        //adicionar no addClass a classe que ira criar a tabela
        Configuration configuration = new Configuration();
        configuration.addClass(ClasseUm.class)
        configuration.addClass(ClasseDois.class);

        SchemaExport se = new SchemaExport(configuration);
        se.create(true, true);
        // aqui o primeiro true gera o script de criação do banco ,
        // o segundo se voce quer executar ele no banco ou não
	}
}
No seu arquivo de configuração, coloque essa url
&lt;property name="hibernate.connection.url"&gt;jdbc:hsqldb:file:./banco/estudo_hibernate;shutdown=true;&lt;/property&gt;

Dentro do diretório raiz do seu projeto, será criada uma pasta chamada banco e dentro dela estarão os arquivos do bando de dados criado.

Para criar o banco, coloque essa configurações
&lt;property name="hibernate.connection.username"&gt;sa&lt;/property&gt;
&lt;property name="hibernate.connection.password"&gt;&lt;/property&gt;

Depois de criado, entre no diretório banco e abra o arquivo: estudo_hibernate.script

Dai se quizer, pode alterar o user e pass e colocar o que vc quizer, e não esqueça de alterar nas configurações do hibernate depois:
CREATE USER SA PASSWORD ""
GRANT DBA TO SA
//depois
CREATE USER HIBERNATE PASSWORD HIBERNATE 
GRANT DBA TO HIBERNATE

Depois de criar o banco, não execute mais a classe GeraBanco, pq ela irá deletar o banco criado e criar outro. Se precisar inserir mais alguma tabela, apenas adicione na configuração a nova tabela(e não as ja criadas) e então execute novamente esta classe.

litium

E aí!

romarcio o nome do banco de dados vai sair de acordo com a organização de minhas pastas na URL que você mandou eu configurar, né?

Eu fui fazer isso que você falou. Rodei o "GeraBanco" e ele deu uma exceção dizendo que não achou o Pessoa.hbm.xml na pasta pojos. Então eu copiei o XML e coloquei na pasta BIN (uso o eclipse) e depois coloquei na pasta pojos como ele havia pedido. Funcionou, mas deu isso:

27/12/2010 21:38:18 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.1.3
27/12/2010 21:38:18 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
27/12/2010 21:38:18 org.hibernate.cfg.Environment <clinit>
INFO: using CGLIB reflection optimizer
27/12/2010 21:38:18 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
27/12/2010 21:38:18 org.hibernate.cfg.Configuration addClass
INFO: Reading mappings from resource: pojos/Pessoa.hbm.xml
27/12/2010 21:38:18 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: pojos.Pessoa -> pessoa
Exception in thread "main" org.hibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect.
	at org.hibernate.dialect.Dialect.getDialect(Dialect.java:610)
	at org.hibernate.dialect.Dialect.getDialect(Dialect.java:632)
	at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:84)
	at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:59)
	at hsqldb.CriarBanco.main(CriarBanco.java:15)
O engraçado foi que eu coloquei o dialeto certinho no arquivo de configuração do hibernate (hibernate.cfg.xml). Tá até assim a linha:
<property name = "hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
Minha classe está "GeraBanco" está assim:
package hsqldb;

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

import pojos.Pessoa;

public class CriarBanco 
{
	public static void main(String[] args) 
	{
		Configuration configurador = new Configuration();
		configurador.addClass(Pessoa.class);
		
		SchemaExport esquema = new SchemaExport(configurador);
		esquema.create(true, true);
	}

}
E agora?

Abraços!

romarcio

Adiciona esse parâmetro de maneira programática então:

public static void main(String[] args)   
    {  
        Configuration configurador = new Configuration();  
        configurador.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
                          .addClass(Pessoa.class);  
          
        SchemaExport esquema = new SchemaExport(configurador);  
        esquema.create(true, true);  
    }

Se ele não encontrar as outras configurações, vai adicionando elas através do setProperty.

Criado 18 de dezembro de 2010
Ultima resposta 28 de dez. de 2010
Respostas 13
Participantes 2