Mudei de sql para hibernate mas

bem, to refazendo meu projeto que estava em sql e tentando passar ele para hibernate

eu to seguindo o tutorial da apostila F-21 da caelum, uns dos ultimos capitulos fala sobre hibernate

to la fazendo do jeito q explica porém nao ta gerando a tabela

qdo executo o codigo :

AnnotationConfiguration cfg = new AnnotationConfiguration(); cfg.addAnnotatedClass(Estagiario.class); new SchemaExport(cfg).create(true, true);

ele nao gera a tabela
porem se coloco :

AnnotationConfiguration cfg = new AnnotationConfiguration(); cfg.addAnnotatedClass(Estagiario.class); new SchemaExport(cfg).create(true, false);

trocando o segundo argumento do create de true para false ele aparentemente cria a tabela pelo console :

drop table if exists Estagiario create table Estagiario (id bigint not null auto_increment, nome varchar(255), turno varchar(255), primary key (id))

porém, qdo vou verificar nao existe a tabela lá

esse é meu arquivo hibernate.properties :

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

ai na curiosidade, fui tentar adicionar um objeto usando sessao
ai deu uma exception gigante :

Exception in thread "main" org.hibernate.exception.SQLGrammarException: Cannot open connection at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67) 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:424) at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144) at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:94) at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:30) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2154) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2634) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519) at almoxarifado.spike.AdicionaEstagiario.main(AdicionaEstagiario.java:14) Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown database 'teste' at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:868) at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3340) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1238) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2743) at com.mysql.jdbc.Connection.<init>(Connection.java:1553) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:421) ... 19 more

ai entedi q nao ta abrindo conexao, mas como nao se acredito eu que ta tudo certo de acordo com a apostila, ajudem ai gente por favor

Tens que criar o banco primeiro, ele gera só as tabelas.

se for criarum database no mysql isso ja fiz

Te garanto uma coisa, para criar no banco de dados tem que ser:
new SchemaExport(cfg).create(true, true);
O segundo argumento é justamente para criar no banco de dados(true) ou simplesmente mostrar o comando sql no console(false).

Dê uma olhadinha no seu hibernate.properties, na parte da conexão com o Mysql, nunca configurei o hibernate para trabalhar com Mysql, mas acredito que seu problema esteja ai.

Uma questão bem idiota(me desculpe pela pergunta), mas o Mysql está startado, né? :smiley:

Espero ter ajudado.

Abraços.

kra, era no properties mesmo haauhahuahu, arrumei

mas ta dando outro erro agora, to inserindo usando metodo save

mas qdo vo la no command line do mysql e do select * from estagiario

ta retornando empty set

e tento fazer uma busca pelo metodo load e ta dando exception mesmo colocando um id q ja existe :

Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [almoxarifado.business.Estagiario#2] at org.hibernate.impl.SessionFactoryImpl$1.handleEntityNotFound(SessionFactoryImpl.java:377) at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:79) at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:68) at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111) at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:140) at almoxarifado.business.Estagiario$$EnhancerByCGLIB$$c9ce49c7.getId(<generated>) at almoxarifado.spike.AdicionaEstagiario.main(AdicionaEstagiario.java:17)

nao to entendendo, sendo que sempre q cria um objeto e uso save, ele vai incrementando o codigo

entao gente, se alguem puder me ajudar eu agredeço

eu consigo salvar os objetos com o metodo save do da session pq o codigo sempre ta incrementando, porem qdo tento da um load está dando a exception que postei acima dizendo que nao existe essa linha

Tenta assim:

[code]public class GerarBanco {

public static void main(String[] args) {
	Configuration config = new AnnotationConfiguration();
	config.configure();//lê o XML

	SchemaUpdate schemaExport = new SchemaUpdate(config);
	schemaExport.execute(true, true);

}

}[/code]

[code]

org.hibernate.dialect.MySQLDialect jdbc:mysql://localhost/DB com.mysql.jdbc.Driver root root
	<property name="hibernate.show_sql">true</property>
	<property name="hibernate.format_sql">true</property>

	<!-- usar C3P0 Pool de conexões -->

	<property name="hibernate.c3p0.min_size">1</property>
	<property name="hibernate.c3p0.max_size">5</property>
	<property name="hibernate.c3p0.maxIdleTime">200</property>
	<property name="hibernate.c3p0.timeout">180</property>
	<property name="hibernate.c3p0.idle_test_period">100</property>
	<property name="hibernate.c3p0.max-statements">50</property>


	<mapping class="br.com.fireant.acesso.Acesso"/>
	<mapping class="br.com.fireant.cadastro.Cadastro"/>

</session-factory>

[/code]

:smiley:

yay!! funfou :slight_smile: :slight_smile:

brigado Heero