Query usando Hibernate com anotacoes

Ola amigos gostaria de uma utilizar o hibernate sem mapear o objeto pelo xml (por exemplo usuario.hbm.xml) e retornar o resultado de uma query de sql.

Segue o codigo:

Config XML:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql:Estudo_web</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">postgre</property>
        <mapping class="modelo.TbUsuario"/>

    <!-- Configurações de debug -->
        <property name="show_sql">true</property>
        <property name="hibernate.generate_statistics">true</property>
        <property name="hibernate.use_sql_comments">true</property>

    </session-factory>
</hibernate-configuration>

Na classe TbUsuario:


package modelo;
// Generated 23/09/2009 15:40:05 by Hibernate Tools 3.2.1.GA


import javax.persistence.Column;
import javax.persistence.ColumnResult;
import javax.persistence.Entity;
import javax.persistence.EntityResult;
import javax.persistence.FieldResult;
import javax.persistence.Id;
import javax.persistence.SqlResultSetMapping;
import javax.persistence.Table;
import org.hibernate.annotations.NamedNativeQuery;
import org.hibernate.annotations.NamedQuery;

/**
 * TbUsuario generated by hbm2java
 */
@Entity
@Table(name="tb_usuario"
    ,schema="public"
)



public class TbUsuario  implements java.io.Serializable {


     private int CId;
     private String CNome;
     private String CEmail;

    public TbUsuario() {
    }

	
    public TbUsuario(int CId) {
        this.CId = CId;
    }
    public TbUsuario(int CId, String CNome, String CEmail) {
       this.CId = CId;
       this.CNome = CNome;
       this.CEmail = CEmail;
    }
   
     @Id 
    
    @Column(name="c_id", unique=true, nullable=false)
    public int getCId() {
        return this.CId;
    }
    
    public void setCId(int CId) {
        this.CId = CId;
    }
    
    @Column(name="c_nome")
    public String getCNome() {
        return this.CNome;
    }
    
    public void setCNome(String CNome) {
        this.CNome = CNome;
    }
    
    @Column(name="c_email")
    public String getCEmail() {
        return this.CEmail;
    }
    
    public void setCEmail(String CEmail) {
        this.CEmail = CEmail;
    }




}



Classe HibernateUtil:


public class HibernateUtil3 {

    private static SessionFactory factory;


    static {
        AnnotationConfiguration cfg = new AnnotationConfiguration();
        cfg.addAnnotatedClass(TbUsuario.class);
        //.addAnnotatedClass(SuaEntidade2.class);
        factory = cfg.buildSessionFactory();
    }

    public Session getSession() {
        return factory.openSession();
    }
}

Na classe DAO:

public static void buscar_todos() {
        try {

           Session session = new HibernateUtil3().getSession();
           Transaction tx = session.beginTransaction();
            Query select = session.createQuery("select * from tb_usuario");
            List objetos = select.list();
            System.out.println(objetos);


        } catch (HibernateException e1) {
            e1.printStackTrace();

        }
    }

ERRO:

02/10/2009 10:25:52 org.hibernate.cfg.annotations.Version
INFO: Hibernate Annotations 3.3.1.GA
02/10/2009 10:25:52 org.hibernate.cfg.Environment
INFO: Hibernate 3.2.5
02/10/2009 10:25:52 org.hibernate.cfg.Environment
INFO: hibernate.properties not found
02/10/2009 10:25:52 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
02/10/2009 10:25:52 org.hibernate.cfg.Environment
INFO: using JDK 1.4 java.sql.Timestamp handling
02/10/2009 10:25:52 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: modelo.TbUsuario
02/10/2009 10:25:52 org.hibernate.cfg.annotations.EntityBinder bindTable
INFO: Bind entity modelo.TbUsuario on table tb_usuario
02/10/2009 10:25:53 org.hibernate.cfg.AnnotationConfiguration secondPassCompile
INFO: Hibernate Validator not found: ignoring
02/10/2009 10:25:53 org.hibernate.connection.UserSuppliedConnectionProvider configure

WARNING: No connection properties specified - the user must supply JDBC connections
Exception occurred during event dispatching:
java.lang.ExceptionInInitializerError
at DAO.DAO_Usuario.buscar_todos(DAO_Usuario.java:93)
at controle.Controle_usuario.buscar_todos(Controle_usuario.java:99)
at visao.Tela.btn_exibir_todosActionPerformed(Tela.java:307)
at visao.Tela.access$200(Tela.java:23)
at visao.Tela$3.actionPerformed(Tela.java:131)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6041)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5806)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4413)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2440)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:177)
at java.awt.Dialog$1.run(Dialog.java:1045)
at java.awt.Dialog$3.run(Dialog.java:1097)
at java.security.AccessController.doPrivileged(Native Method)
at java.awt.Dialog.show(Dialog.java:1095)
at java.awt.Component.show(Component.java:1422)
at java.awt.Component.setVisible(Component.java:1375)
at java.awt.Window.setVisible(Window.java:806)
at java.awt.Dialog.setVisible(Dialog.java:985)
at visao.Tela.btn_buscarActionPerformed(Tela.java:301)
at visao.Tela.access$500(Tela.java:23)
at visao.Tela$6.actionPerformed(Tela.java:207)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6041)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5806)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4413)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2440)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
Caused by: org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
at org.hibernate.dialect.DialectFactory.determineDialect(DialectFactory.java:57)
at org.hibernate.dialect.DialectFactory.buildDialect(DialectFactory.java:39)
at org.hibernate.cfg.SettingsFactory.determineDialect(SettingsFactory.java:426)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:128)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at util.HibernateUtil3.(HibernateUtil3.java:25)
… 63 more
CONSTRUÍDO COM SUCESSO (tempo total: 8 segundos)

Obrigado pela atenção de todos.

Cara, voce nao informou o dialeto que esta usando, por exemplo: SQLServerDialect; PostgreSQLDialect, etc. É o que informa o seu log. As informacoes que voce TEM que passar para o hibernate sobre a forma que realizara a conexao com a base sao: dialeto, url da base, driver, usuario e senha.

Espero ter ajudado!

Mais eu passei isso no xml do config mais axo q nao to passando ele no hibernateutil como posso fazelo ?

org.hibernate.dialect.PostgreSQLDialect
org.postgresql.Driver
jdbc:postgresql:Estudo_web
postgres
postgre

Esse URL esta estranha! Veja se isso resolve:

jdbc:postgresql://localhost:5342/Estudo_web

O problema nao esta ae nao quem gerou isso foi o proprio netbeans eu mudei mais nao tive sucesso… eu nao teria q passar o caminho desse xml no hibernateutil?

Entao cara, tudo me leva a crer que o Hibernate nao consegue conectar com a base, veja a seguinte linha:

WARNING: No connection properties specified - the user must supply JDBC connections
Exception occurred during event dispatching:
java.lang.ExceptionInInitializerError
at DAO.DAO_Usuario.buscar_todos(DAO_Usuario.java:93) 

Entendi eu ja tinha percebido isso por isso q axo q o problema ta aki:
Nao sei como passar o caminho do config do xml… como pro exemplo cfg.configure("/hibernate/hibernate.cfg.xml");

AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass(TbUsuario.class);
factory = cfg.buildSessionFactory();

Tente algo assim:

File file = new File(\\hibernate\\hibernate.cfg.xml);
cfg.configure(file);

Fiz tudo denovo deu um erro no drive do postgre nao entendi o pq mais concertei ele, agora diz q a classe do TbUsuario nao foi mapeada.

Classe TbUsuario:


package modelo;
// Generated 02/10/2009 12:17:21 by Hibernate Tools 3.2.1.GA


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * TbUsuario generated by hbm2java
 */
@Entity
@Table(name="tb_usuario"
    ,schema="public"
)
public class TbUsuario  implements java.io.Serializable {


     private int CId;
     private String CNome;
     private String CEmail;

    public TbUsuario() {
    }

	
    public TbUsuario(int CId) {
        this.CId = CId;
    }
    public TbUsuario(int CId, String CNome, String CEmail) {
       this.CId = CId;
       this.CNome = CNome;
       this.CEmail = CEmail;
    }
   
     @Id 
    
    @Column(name="c_id", unique=true, nullable=false)
    public int getCId() {
        return this.CId;
    }
    
    public void setCId(int CId) {
        this.CId = CId;
    }
    
    @Column(name="c_nome")
    public String getCNome() {
        return this.CNome;
    }
    
    public void setCNome(String CNome) {
        this.CNome = CNome;
    }
    
    @Column(name="c_email")
    public String getCEmail() {
        return this.CEmail;
    }
    
    public void setCEmail(String CEmail) {
        this.CEmail = CEmail;
    }




}

Classe HibernateUtil:


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

import java.io.File;
import modelo.TbUsuario;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 *
 * @author Administrador
 */
public class HibernateUtil3 {

    private static SessionFactory factory;


    static {
        AnnotationConfiguration cfg = new AnnotationConfiguration();
        cfg.configure("\\hibernate\\hibernate.cfg.xml");
        //File file = new File("\\hibernate\\hibernate.cfg.xml");
       //cfg.configure(file);
        cfg.addAnnotatedClass(TbUsuario.class);
        //.addAnnotatedClass(SuaEntidade2.class);
        factory = cfg.buildSessionFactory();
    }

    public Session getSession() {
        return factory.openSession();
    }
}

Configuracao XML:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Estudo_web</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">postgre</property>
    <mapping class="modelo.TbUsuario"/>
  </session-factory>
</hibernate-configuration>

ERRO:

INFO: Not binding factory to JNDI, no JNDI name configured
org.hibernate.hql.ast.QuerySyntaxException: tb_usuario is not mapped [select c_id from tb_usuario]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:158)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87)

Entao cara, voce tem que incluir o TbUsuario.hbm.xml na configuracao da Sessison do Hibernate. Vou te mandar um exemplo de um hibernate.cfg.xml que fiz:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
	<!-- Database connection settings -->
		
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/locadora</property>
		<property name="connection.username">zzz</property>
		<property name="connection.password">xxx</property>
		<!-- JDBC connection pool (use the built-in) -->
		<property name="connection.pool_size">1</property>
		<!-- SQL dialect -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- Enable Hibernate's automatic session context management -->
		<property name="current_session_context_class">thread</property>
		<!-- Disable the second-level cache -->
		<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">true</property>
		
		<!-- Drop and re-create the database schema on startup -->
		<!--<property name="hbm2ddl.auto">create</property>-->
		
                 //incluindo os mapeamentos
		<mapping resource="com/vinicius/locadora/entity/Categoria.hbm.xml"/>
		<mapping resource="com/vinicius/locadora/entity/CategoriaCliente.hbm.xml"/>
		<mapping resource="com/vinicius/locadora/entity/ClienteDependente.hbm.xml"/>
		<mapping resource="com/vinicius/locadora/entity/ClienteTitular.hbm.xml"/>
		<mapping resource="com/vinicius/locadora/entity/Titulo.hbm.xml"/>
		<mapping resource="com/vinicius/locadora/entity/ValorTitulo.hbm.xml"/>
		<mapping resource="com/vinicius/locadora/entity/Promocao.hbm.xml"/>
                <mapping resource="com/vinicius/locadora/entity/TituloLocado.hbm.xml"/>
                <mapping resource="com/vinicius/locadora/entity/Grupo.hbm.xml"/>
		<mapping resource="com/vinicius/locadora/entity/Menu.hbm.xml"/>
		<mapping resource="com/vinicius/locadora/entity/Permissao.hbm.xml"/>
		<mapping resource="com/vinicius/locadora/entity/Usuario.hbm.xml"/>
		
		
	</session-factory>
		
	
	
</hibernate-configuration>

Não tem como fugir desse hbm.xml?

O mercado de trabalho costuma usar o hbm.xml ?

se nao tiver eu faco com ele mesmo fazer o que né =(

eu consigo inserir sem usar hbm.xml.

Olha, eu nunca trabalhei com annotation! Imagino que em algum lugar voce tenha que dizer ao hibernate como realizar sua conexao com a base, quais serão seu entities beans, etc. Faço isso no hibernate.cfg.xml.

Cara, já sei onde esto o erro: esta na sua query…rsrs. Faça o seguinte:

 public static void buscar_todos() {  
   try {  
     Session session = new HibernateUtil3().getSession();  
     Transaction tx = session.beginTransaction();  
     //Query select = session.createQuery("select * from tb_usuario"); 
     //Voce tem que passar um HQL ao inves de SQL puro
     Query select = session.createQuery("FROM TbUsuario"); 
     List objetos = select.list();  
     System.out.println(objetos);  
   } catch (HibernateException e1) {  
    e1.printStackTrace();  
  }  
  
}  

Ta ok entaum vo migrar para o Hibernate com XML entaum.

Obrigado pela ajuda.

Cara, antes de migrar tente a alteracao da query abaixo:

public static void buscar_todos() {  
   try {  
     Session session = new HibernateUtil3().getSession();  
     Transaction tx = session.beginTransaction();  
     //Query select = session.createQuery("select * from tb_usuario"); 
     //Voce tem que passar um HQL ao inves de SQL puro
     Query select = session.createQuery("FROM TbUsuario"); 
     List<TbUsuario> usuarios = (List<TbUsuario>)select.list();  
     for(TbUsuario u : usuarios){
          System.out.println(u.getCId());
     }  
   } catch (HibernateException e1) {  
    e1.printStackTrace();  
  }  
  
}  

[Resolvido] agora deu certo vo te que ler sobre esse HQL espero q nao mude muito o sql. 8)

Muito obrigado pela ajuda.