Hibernate+netbeans

5 respostas
F

Boa Tarde!
Através do Netbeans 6.8 estava tentando criar minha camada de persistencia com um banco de dados que ja estava pronto.
Daí criei o projeto cliquei em novo > outro > e em hibirnate “Assitente para configuração do hibernate”
depois > “Assitente para engenharia reversa do hibernate”
depois “Arquivos de mapeamento do hibernate e POJOs de Banco de Dados”
e depois HibernateUtil.java

Até ai blz. Criou tudo sem dar erro.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 10/04/2010 18:32:00 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
  <class catalog="svi_site" name="javaapplication3.Categoria" table="categoria">
    <id name="idcategoria" type="java.lang.Integer">
      <column name="idcategoria"/>
      <generator class="identity"/>
    </id>
    <property name="nome" type="string">
      <column length="50" name="nome"/>
    </property>
  </class>
</hibernate-mapping>
package javaapplication3;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author FFGM
 */
public class NewHibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
Quando fui testar
 public static void main(String[] args) {
        Session session = NewHibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        Categoria c = new Categoria();
        c.setIdcategoria(5);
        c.setNome("HIBERNATE");
        session.save(c);
        transaction.commit();
        session.close();
        System.out.println("Salvo com sucesso!");
    }
run:
11/04/2010 11:33:31 org.hibernate.cfg.annotations.Version <clinit>
INFO: Hibernate Annotations 3.3.1.GA
11/04/2010 11:33:31 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.5
11/04/2010 11:33:31 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
11/04/2010 11:33:31 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
11/04/2010 11:33:31 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
11/04/2010 11:33:31 org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
11/04/2010 11:33:31 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
11/04/2010 11:33:31 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : hibernate.hbm.xml
11/04/2010 11:33:31 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : javaapplication3/Categoria.hbm.xml
11/04/2010 11:33:31 org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
11/04/2010 11:33:31 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: javaapplication3.Categoria -> categoria
11/04/2010 11:33:31 org.hibernate.cfg.AnnotationConfiguration secondPassCompile
INFO: Hibernate Validator not found: ignoring
11/04/2010 11:33:31 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
11/04/2010 11:33:31 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 20
11/04/2010 11:33:31 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
11/04/2010 11:33:31 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/svi_site
11/04/2010 11:33:31 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {user=root, password=****}
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: RDBMS: MySQL, version: 5.1.45-community
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.6 ( Revision: ${svn.Revision} )
11/04/2010 11:33:32 org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
11/04/2010 11:33:32 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
11/04/2010 11:33:32 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): enabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 2
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL inserts for batching: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
11/04/2010 11:33:32 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JPA-QL strict compliance: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.NoCacheProvider
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
11/04/2010 11:33:32 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Named query checking : enabled
11/04/2010 11:33:32 org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
11/04/2010 11:33:32 org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
Salvo com sucesso!
CONSTRUÍDO COM SUCESSO (tempo total: 0 segundos)

Não laça exceptions mas tambem não cadastra

5 Respostas

romarcio

Posta pra nós o seu hibernate.cfg.xml.

E outra coisa, quando faz o insert, no seu banco vc setou o id da tabela como auto-incremento ? Se setou não deve fazer o c.setIdcategoria(5), pq o hibernate que controla isso, dai ele pode ter se perdido de alguma maneira.

Faz assim, cria o método do insert com o try catch, para ver a exceção lançada.

public static void main(String[] args) {
		Session session = null;
	    try {
			Session session = NewHibernateUtil.getSessionFactory().openSession();
			Transaction transaction = session.beginTransaction();
			Categoria c = new Categoria();
			c.setIdcategoria(5);
			c.setNome("HIBERNATE");
			session.save(c);
			transaction.commit();
			System.out.println("Registro Inserido!");
		}catch (Exception  e) {
            System.out.println(e.getMessage());
        } finally {
            session.flush();
            session.close();
        }
    }
F

romarcio:
Posta pra nós o seu hibernate.cfg.xml.

E outra coisa, quando faz o insert, no seu banco vc setou o id da tabela como auto-incremento ? Se setou não deve fazer o c.setIdcategoria(5), pq o hibernate que controla isso, dai ele pode ter se perdido de alguma maneira.

Faz assim, cria o método do insert com o try catch, para ver a exceção lançada.

public static void main(String[] args) {
		Session session = null;
	    try {
			Session session = NewHibernateUtil.getSessionFactory().openSession();
			Transaction transaction = session.beginTransaction();
			Categoria c = new Categoria();
			c.setIdcategoria(5);
			c.setNome("HIBERNATE");
			session.save(c);
			transaction.commit();
			System.out.println("Registro Inserido!");
		}catch (Exception  e) {
            System.out.println(e.getMessage());
        } finally {
            session.flush();
            session.close();
        }
    }


Segue o hibernate.cfg.xml.

<?xml version="1.0" encoding="UTF-8"?> org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/svi_site root root

No meu banco a tabela é auto incremento.
CREATE TABLE categoria (
idcategoria int(10) unsigned NOT NULL AUTO_INCREMENT,
nome varchar(50) DEFAULT NULL,
PRIMARY KEY (idcategoria)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

Saída para exução do código :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication3;

import org.hibernate.Transaction;
import org.hibernate.classic.Session;

/**
 *
 * @author FFGM
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Session session = null;
        try {
            session = NewHibernateUtil.getSessionFactory().openSession();
            Transaction transaction = session.beginTransaction();
            Categoria c = new Categoria();
            c.setNome("HIBERNATE");
            session.save(c);
            transaction.commit();
            System.out.println("Registro Inserido!");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            session.flush();
            session.close();
        }
    }
}
run:

11/04/2010 13:55:10 org.hibernate.cfg.annotations.Version 

INFO: Hibernate Annotations 3.3.1.GA

11/04/2010 13:55:10 org.hibernate.cfg.Environment 

INFO: Hibernate 3.2.5

11/04/2010 13:55:10 org.hibernate.cfg.Environment 

INFO: hibernate.properties not found

11/04/2010 13:55:10 org.hibernate.cfg.Environment buildBytecodeProvider

INFO: Bytecode provider name : cglib

11/04/2010 13:55:10 org.hibernate.cfg.Environment 

INFO: using JDK 1.4 java.sql.Timestamp handling

11/04/2010 13:55:10 org.hibernate.cfg.Configuration configure

INFO: configuring from resource: /hibernate.cfg.xml

11/04/2010 13:55:10 org.hibernate.cfg.Configuration getConfigurationInputStream

INFO: Configuration resource: /hibernate.cfg.xml

11/04/2010 13:55:10 org.hibernate.cfg.Configuration addResource

INFO: Reading mappings from resource : hibernate.hbm.xml

11/04/2010 13:55:10 org.hibernate.cfg.Configuration addResource

INFO: Reading mappings from resource : javaapplication3/Categoria.hbm.xml

11/04/2010 13:55:10 org.hibernate.cfg.Configuration doConfigure

INFO: Configured SessionFactory: null

11/04/2010 13:55:10 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues

INFO: Mapping class: javaapplication3.Categoria -> categoria

11/04/2010 13:55:10 org.hibernate.cfg.AnnotationConfiguration secondPassCompile

INFO: Hibernate Validator not found: ignoring

11/04/2010 13:55:10 org.hibernate.connection.DriverManagerConnectionProvider configure

INFO: Using Hibernate built-in connection pool (not for production use!)

11/04/2010 13:55:10 org.hibernate.connection.DriverManagerConnectionProvider configure

INFO: Hibernate connection pool size: 20

11/04/2010 13:55:10 org.hibernate.connection.DriverManagerConnectionProvider configure

INFO: autocommit mode: false

11/04/2010 13:55:10 org.hibernate.connection.DriverManagerConnectionProvider configure

INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/svi_site

11/04/2010 13:55:10 org.hibernate.connection.DriverManagerConnectionProvider configure

INFO: connection properties: {user=root, password=****}

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: RDBMS: MySQL, version: 5.1.45-community

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.6 ( Revision: ${svn.Revision} )

11/04/2010 13:55:10 org.hibernate.dialect.Dialect 

INFO: Using dialect: org.hibernate.dialect.MySQLDialect

11/04/2010 13:55:10 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory

INFO: Using default transaction strategy (direct JDBC transactions)

11/04/2010 13:55:10 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup

INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Automatic flush during beforeCompletion(): disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Automatic session close at end of transaction: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: JDBC batch size: 15

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: JDBC batch updates for versioned data: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Scrollable result sets: enabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: JDBC3 getGeneratedKeys(): enabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Connection release mode: auto

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Maximum outer join fetch depth: 2

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Default batch fetch size: 1

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Generate SQL with comments: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Order SQL updates by primary key: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Order SQL inserts for batching: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory

INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory

11/04/2010 13:55:10 org.hibernate.hql.ast.ASTQueryTranslatorFactory 

INFO: Using ASTQueryTranslatorFactory

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Query language substitutions: {}

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: JPA-QL strict compliance: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Second-level cache: enabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Query cache: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory createCacheProvider

INFO: Cache provider: org.hibernate.cache.NoCacheProvider

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Optimize cache for minimal puts: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Structured second-level cache entries: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Statistics: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Deleted entity synthetic identifier rollback: disabled

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Default entity-mode: pojo

11/04/2010 13:55:10 org.hibernate.cfg.SettingsFactory buildSettings

INFO: Named query checking : enabled

11/04/2010 13:55:10 org.hibernate.impl.SessionFactoryImpl 

INFO: building session factory

11/04/2010 13:55:10 org.hibernate.impl.SessionFactoryObjectFactory addInstance

INFO: Not binding factory to JNDI, no JNDI name configured

Registro Inserido!

CONSTRUÍDO COM SUCESSO (tempo total: 1 segundo)

Agora inseriu! O que estava errado era só o auto increment?
Por isso não estava inserindo?

romarcio

Com certeza era isso sim.

F

romarcio:
Com certeza era isso sim.

Tenho mais um duvida. Se eu fizer um sistema com o hibernate quando for destribuílo como fica a questão da senha e usuario do banco? Isso fica de fora do programa quando eu for gerar o instalador?

romarcio

Fica nesse arquivo hibernate.cfg.xml ou em um arquivo chamado hibernate.properties. Ou então vc pode setar a propriedade de senha e usuario do banco direto na classe da sessionfactory.
Mas usualmente fica nos arquivos mesmo, isso para aplicação desktop.

Quando for uma aplicação Web, dai pode-se mudar isso, passando a conexão com bando por um arquivo xml que ficaria dentro do servidor web. Dai dependendo do servidor, glassfish, jboss, jonas, etc, pode mudar um pouco a estrutura do xml, mas as propriedades geralmente são as mesmas.

Criado 11 de abril de 2010
Ultima resposta 12 de abr. de 2010
Respostas 5
Participantes 2