Ajuda com Hibernate -- Erro ao criar tabela no banco

8 respostas
VanHelsing

Boa noite pessoal,
Estou fazendo alguns testes com o Hibernate e estou encontrando uma dificuldade na hora do Hibernate criar a tabela a partir da minha classe.
Segue minha Classe Usuario

@Entity
@Table
public class Usuarios {

	private static final long serialVersionUID = 1L;
	
	@Id
	@Column
	private Integer id;
	
	@Column(nullable=false,length=50)
	private String nome;
	
	@Column(nullable=false,length=6)
	private String senha;

       
        ....   Getters e Setters... Equal e Hascode...        
}

Minha Classe Main

public class Principal {

   Public static void main(String[] args) {
        SessionFactory sf = new AnnotationConfiguration()
           .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
           .setProperty("hibernate.connection.driver_class","com.mysql.jdbc.Driver")
           .setProperty("hibernate.connection.url","jdbc:mysql://localhost:3306/test")
           .setProperty("hibernate.connection.username", "root")
           .setProperty("hibernate.connection.password", "senha")
           .setProperty("hibernate.hbm2dll.auto","update")
           .setProperty("hibernate.show_sql","false")
           .setProperty("hibernate.format_sql","true")
           .setProperty("hibernate.c3p0.acquire_incremente","1")        
           .setProperty("hibernate.c3p0.idle_test_period","100")
           .setProperty("hibernate.c3p0.max_size","10")
           .setProperty("hibernate.c3p0.max_statements","0")
           .setProperty("hibernate.c3p0.min_size","5")
           .setProperty("hibernate.c3p0.timeout","100")       
        
          .addAnnotatedClass(Usuarios.class)
          .buildSessionFactory();
       
        // Abre Sessão
        Session session = sf.openSession();
        session.beginTransaction();

        // Persiste os Dados
        Usuarios usr = new Usuarios();
        usr.setId(1);
        usr.setNome("Usuario1");
        usr.setSenha("123");
        
        session.save(usr);
        
        
        // Fecha Sessão
        session.beginTransaction().commit();
        session.close();
        sf.close();
	}
}

Quando eu rodo da o seguinte erro. Ja procurei na net e nao achei nada… Me ajudem ai por favor…

Caused by: java.sql.BatchUpdateException: Table 'bd.usuarios' doesn't exist
	at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666)
	at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082)
	at com.mchange.v2.sql.filter.FilterPreparedStatement.executeBatch(FilterPreparedStatement.java:260)
	at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
	at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
	... 8 more
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
	at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
	at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
	at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
	at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
	at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
	at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
	at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
	at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
	at Principal.main(Principal.java:43)

8 Respostas

mateusprado

Ola.
Tente alterar essa linha:

.setProperty("hibernate.connection.url","jdbc:mysql://localhost:3306/test") ;

Para:

.setProperty("hibernate.connection.url","jdbc:mysql://localhost/test") ;

Antes verifique se seu banco de dados test existe.

[ ]s,

VanHelsing

Não deu certo !!! :cry:

R

no banco, qual é o nome da tabela e do banco?

Marky.Vasconcelos

Voce criou a tabela?

Se não… o hibernate também pode te ajudar…

AnnotationConfiguration cfg = new AnnotationConfiguration()
            .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")  
            .setProperty("hibernate.connection.driver_class","com.mysql.jdbc.Driver")  
            .setProperty("hibernate.connection.url","jdbc:mysql://localhost:3306/test")  
            .setProperty("hibernate.connection.username", "root")  
            .setProperty("hibernate.connection.password", "senha")  
            .setProperty("hibernate.hbm2dll.auto","update")  
            .setProperty("hibernate.show_sql","false")  
            .setProperty("hibernate.format_sql","true")  
            .setProperty("hibernate.c3p0.acquire_incremente","1")          
            .setProperty("hibernate.c3p0.idle_test_period","100")  
            .setProperty("hibernate.c3p0.max_size","10")  
            .setProperty("hibernate.c3p0.max_statements","0")  
            .setProperty("hibernate.c3p0.min_size","5")  
            .setProperty("hibernate.c3p0.timeout","100")         
          
           .addAnnotatedClass(Usuarios.class);
        SchemaUpdate schema = new SchemaUpdate(cfg);
        schema.execute(true,true);
VanHelsing

Mas é isso exatamente que to querendo fazer…
A partir da minha classe o Hibernate crie a tabela pra mim, ou altere, caso eu mude alguma propriedade da classe.

“hibernate.hbm2dll.auto”,“update”

Ps. O banco existe, mas ta tabela Usuarios nao

Marky.Vasconcelos

Nem vi essa propriedade… mas voce tem certeza que essa propriedade faz isso mesmo?

Não sabia que ele criava sozinho criando a session…

VanHelsing

Faz sim… Ja vi varios exemplos…

Mas aqui nao ta dando certo…

Ja verifiquei os JAR´s do Hibernate que estou carregando e tudo mais…

Jeferson_Manetti

bom particularmente não gosto de fazer aas configurações programaticamente... prefiro o hibernate.cfg.xml....
mais isso e preferencia minha...

pra gerar as tabelas.... coloque isso em um classe com metodo main e execute =)

AnnotationConfiguration cfg = new AnnotationConfiguration()  
               .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")    
               .setProperty("hibernate.connection.driver_class","com.mysql.jdbc.Driver")    
               .setProperty("hibernate.connection.url","jdbc:mysql://localhost:3306/test")    
               .setProperty("hibernate.connection.username", "root")    
               .setProperty("hibernate.connection.password", "senha")      
               .setProperty("hibernate.show_sql","true")    
               .setProperty("hibernate.format_sql","true")    
               .setProperty("hibernate.c3p0.acquire_incremente","1")            
               .setProperty("hibernate.c3p0.idle_test_period","100")    
               .setProperty("hibernate.c3p0.max_size","10")    
               .setProperty("hibernate.c3p0.max_statements","0")    
               .setProperty("hibernate.c3p0.min_size","5")    
               .setProperty("hibernate.c3p0.timeout","100")                     
              .addAnnotatedClass(Usuarios.class);  

           SchemaExport schema = new SchemaExport(cfg);  
           schema.execute(true,true);
na sua clase usuario... mudei uma coisinha....
@Entity  
   public class Usuarios {  
     
       private static final long serialVersionUID = 1L;  
         
       @Id
       @GeneratedValue(strategy=GenerationType.AUTO) 
       private Integer id;  
         
       @Column(nullable=false,length=50)  
       private String nome;  
         
       @Column(nullable=false,length=6)  
       private String senha;  
     
            
           ....   Getters e Setters... Equal e Hascode...          
   }

e so isso...
não e pra dar problema...

se vc quiser... me passa seu e-mail por MP q eu ti mando um exemplo q eu fiz no hibernate...

frmz

Criado 14 de março de 2009
Ultima resposta 16 de mar. de 2009
Respostas 8
Participantes 5