Como definir o tipo do Nativiquery?

Senhores tenho que fazer uma consulta como segue abaixo:

EntityManager em = getEntityManager();
        String sql = "select CONVERT(VARCHAR(10),DATA,103) as data," 
        + "CONVERT(MONEY,((CAST(COUNT(SITUACAO) as float) - CAST(SUM(SITUACAO) as float))/CAST(COUNT(SITUACAO) as float)) * 100,0)"
        + "as INDICE from EQUIPAMENTOS a"
        + "join STATUS_EQUIPAMENTO b"
        + "on a.STATUS_EQUIPAMENTO = b.ID_EQUIP"
        + "where a.COMUNICACAO <> 1 and a.TIPOEQ BETWEEN tipoeq1 and tipoeq2 and DATA BETWEEN data_start and data_end and a.REGIONAL = regional"
        + "GROUP BY b.DATA"
        + "order by b.DATA";

neste caso como deve ser o retorno da informação, digo qual o tipo do liste que deve ser considerado uma vez que estou pegando informações de várias tabelas distintas???

Em outros casos ficou bem óbvio, como na consulta abaixo que tá funcionando normalmente:

EntityManager em = getEntityManager();
        try{
            List<Equipamentos> equip = (List<Equipamentos>)em.createNativeQuery
            ("SELECT * FROM EQUIPAMENTOS WHERE " + columm + " = " + value, Equipamentos.class)
                              .getResultList(); 
            return equip;
        }finally{
            em.close();
        }

Ou seja, a pesquisa é na tabela Equipamentos então a lista é do tipo Equipamentos e a Nativequery também é do tipo Equipamentos.class.

Mas no caso de ter um Join com várias tabelas, como fica?

Grato,

Mauricio.

Você teria que criar uma classe para receber esse resultado.

De uma olhada nesse post: JPA Consultas e Dicas.

Ou retornar um List<Object[]> hehehe, então no caso é melhor fazer o que o Hébert falou mesmo :slight_smile:

Hummm, entendi…

Vou fazer aqui e retorno.

Grato,

Maurício.

Hebert,

 Tem como você explicar melhor esse trecho do código do seu exemplo???

 Por que tem de converter o result tanto para Person quanto para Adress???
Object[] result = (Object[]) query.getSingleResult();         
Person personWithAdress = (Person) result[0];        
Address address = (Address) result[1]; 

Grato,

Maurício.

[quote=maurijava]Hebert,

 Tem como você explicar melhor esse trecho do código do seu exemplo???

 Por que tem de converter o result tanto para Person quanto para Adress???
Object[] result = (Object[]) query.getSingleResult();         
Person personWithAdress = (Person) result[0];        
Address address = (Address) result[1]; 

Grato,

Maurício.[/quote]Por que sua query é native.

[quote=Hebert Coelho][quote=maurijava]Hebert,

 Tem como você explicar melhor esse trecho do código do seu exemplo???

 Por que tem de converter o result tanto para Person quanto para Adress???
Object[] result = (Object[]) query.getSingleResult();         
Person personWithAdress = (Person) result[0];        
Address address = (Address) result[1]; 

Grato,

Maurício.[/quote]Por que sua query é native.[/quote]

Certo, mas se a consulta retornar uma lista de resultados, como eu vou imprimir isso utilizando um for por exemplo?

Não poderia ser:

for(Object imp: resut){
System.out.println(imp.toString);
}

Não sei se deu para você entender minha intenção...

Grato,

Usa named native SQL ou Transformers

Pessoal,

 Tentei fazer assim:

Método que chama a consulta:

public List<Object> calculeIndiceGprs(int tipoeq1, int tipoeq2, String data_start, String data_end, int regional){
        EntityManager em = getEntityManager();
        String sql = "select CONVERT(VARCHAR(10),DATA,103) as data, " 
        + "CONVERT(MONEY,((CAST(COUNT(SITUACAO) as float) - CAST(SUM(SITUACAO) as float))/CAST(COUNT(SITUACAO) as float)) * 100,0) "
        + "as INDICE from EQUIPAMENTOS a "
        + "join STATUS_EQUIPAMENTO b "
        + "on a.STATUS_EQUIPAMENTO = b.ID_EQUIP "
        + "where a.COMUNICACAO <> 1 and a.TIPOEQ BETWEEN " + tipoeq1 + " and " + tipoeq2 + " and  DATA BETWEEN " + data_start + " and " + data_end + " and  a.REGIONAL = " + regional
        + "GROUP BY b.DATA "
        + "order by b.DATA ";
        try{
            List<Object> indice = (List<Object>)em.createNativeQuery
            (sql, Equipamentos.MAPPING_CALCULA_INDICE_GPRS).getResultList(); 
            return indice;
        }finally{
            em.close();
        }
    }

Método main que executa o método:

public static void main(String[] args) {
        
       EquipamentosJpaController equip = new EquipamentosJpaController(Persistence.createEntityManagerFactory("ControlePU"));
       
       List<Object> result = equip.calculeIndiceGprs(1, 5, "'16-02-13'", "'22-02-13'", 1);
       
        for (int i = 0; i < args.length; i++) {
            Equipamentos equipamentos = (Equipamentos)result.get(i);
            System.out.println(equipamentos);
        }
              
        
        
    }

Classe de entidade que tem o @SqlResult:

@Entity
@Table(name = "EQUIPAMENTOS")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Equipamentos.findAll", query = "SELECT e FROM Equipamentos e"),
    @NamedQuery(name = "Equipamentos.findByCodigo", query = "SELECT e FROM Equipamentos e WHERE e.codigo = :codigo"),
    @NamedQuery(name = "Equipamentos.findBySubestacao", query = "SELECT e FROM Equipamentos e WHERE e.subestacao = :subestacao"),
    @NamedQuery(name = "Equipamentos.findByAlimentador", query = "SELECT e FROM Equipamentos e WHERE e.alimentador = :alimentador"),
    @NamedQuery(name = "Equipamentos.findByDistancia", query = "SELECT e FROM Equipamentos e WHERE e.distancia = :distancia"),
    @NamedQuery(name = "Equipamentos.findByPreventiva", query = "SELECT e FROM Equipamentos e WHERE e.preventiva = :preventiva"),
    @NamedQuery(name = "Equipamentos.findByUltimaInspecao", query = "SELECT e FROM Equipamentos e WHERE e.ultimaInspecao = :ultimaInspecao"),
    @NamedQuery(name = "Equipamentos.findByStatusEquipamento", query = "SELECT e FROM Equipamentos e WHERE e.statusEquipamento = :statusEquipamento")})
@SqlResultSetMappings({
         @SqlResultSetMapping(name="calculaIndiceGprs",
            entities={
                @EntityResult(entityClass=Equipamentos.class),
                @EntityResult(entityClass=StatusEquipamento.class),
            },
            columns={@ColumnResult(name="indece")}
            )}
        )
public class Equipamentos implements Serializable {
    private static final long serialVersionUID = 1L;
    public static final String MAPPING_CALCULA_INDICE_GPRS = "calculaIndiceGprs";
...
//Continua o código...

Tá dando esse erro:

INFO: Hibernate EntityManager 3.3.2.GA
[EL Info]: 2013-02-23 16:31:35.192--ServerSession(12941681)--EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
[EL Warning]: 2013-02-23 16:31:35.745--ServerSession(12941681)--Reverting the lazy setting on the OneToOne or ManyToOne attribute [regional] for the entity class [class br.com.mda.entity.Equipamentos] since weaving was not enabled or did not occur.
[EL Warning]: 2013-02-23 16:31:35.746--ServerSession(12941681)--Reverting the lazy setting on the OneToOne or ManyToOne attribute [empresa] for the entity class [class br.com.mda.entity.Equipamentos] since weaving was not enabled or did not occur.
[EL Warning]: 2013-02-23 16:31:35.746--ServerSession(12941681)--Reverting the lazy setting on the OneToOne or ManyToOne attribute [endereco] for the entity class [class br.com.mda.entity.Equipamentos] since weaving was not enabled or did not occur.
[EL Warning]: 2013-02-23 16:31:35.746--ServerSession(12941681)--Reverting the lazy setting on the OneToOne or ManyToOne attribute [acessorio] for the entity class [class br.com.mda.entity.Equipamentos] since weaving was not enabled or did not occur.
[EL Warning]: 2013-02-23 16:31:35.746--ServerSession(12941681)--Reverting the lazy setting on the OneToOne or ManyToOne attribute [comunicacao] for the entity class [class br.com.mda.entity.Equipamentos] since weaving was not enabled or did not occur.
[EL Warning]: 2013-02-23 16:31:35.746--ServerSession(12941681)--Reverting the lazy setting on the OneToOne or ManyToOne attribute [tipoeq] for the entity class [class br.com.mda.entity.Equipamentos] since weaving was not enabled or did not occur.
[EL Info]: 2013-02-23 16:31:36.007--ServerSession(12941681)--file:/C:/Users/mda/Documents/NetBeansProjects/Controle/build/web/WEB-INF/classes/_ControlePU login successful
[EL Warning]: 2013-02-23 16:31:36.094--UnitOfWork(28121438)--Exception [EclipseLink-6044] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.QueryException
Exception Description: The primary key read from the row [DatabaseRecord(
	EQUIPAMENTOS.CODIGO => null
	EQUIPAMENTOS.ALIMENTADOR => null
	EQUIPAMENTOS.DISTANCIA => null
	EQUIPAMENTOS.PREVENTIVA => null
	EQUIPAMENTOS.STATUS_EQUIPAMENTO => null
	EQUIPAMENTOS.SUBESTACAO => null
	EQUIPAMENTOS.ULTIMA_INSPECAO => null
	EQUIPAMENTOS.ACESSORIO => null
	EQUIPAMENTOS.COMUNICACAO => null
	EQUIPAMENTOS.EMPRESA => null
	EQUIPAMENTOS.Endereco => null
	EQUIPAMENTOS.REGIONAL => null
Exception in thread "main" Local Exception Stack: 
	EQUIPAMENTOS.TIPOEQ => null)] during the execution of the query was detected to be null.  Primary keys must not contain null.
Query: ResultSetMappingQuery(referenceClass=Equipamentos sql="select CONVERT(VARCHAR(10),DATA,103) as data, CONVERT(MONEY,((CAST(COUNT(SITUACAO) as float) - CAST(SUM(SITUACAO) as float))/CAST(COUNT(SITUACAO) as float)) * 100,0) as INDICE from EQUIPAMENTOS a join STATUS_EQUIPAMENTO b on a.STATUS_EQUIPAMENTO = b.ID_EQUIP where a.COMUNICACAO <> 1 and a.TIPOEQ BETWEEN 1 and 5 and  DATA BETWEEN '16-02-13' and '22-02-13' and  a.REGIONAL = 1GROUP BY b.DATA order by b.DATA ")
Exception [EclipseLink-6044] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.QueryException
Exception Description: The primary key read from the row [DatabaseRecord(
	EQUIPAMENTOS.CODIGO => null
	EQUIPAMENTOS.ALIMENTADOR => null
	EQUIPAMENTOS.DISTANCIA => null
	EQUIPAMENTOS.PREVENTIVA => null
	EQUIPAMENTOS.STATUS_EQUIPAMENTO => null
	EQUIPAMENTOS.SUBESTACAO => null
	EQUIPAMENTOS.ULTIMA_INSPECAO => null
	EQUIPAMENTOS.ACESSORIO => null
	EQUIPAMENTOS.COMUNICACAO => null
	EQUIPAMENTOS.EMPRESA => null
	EQUIPAMENTOS.Endereco => null
	EQUIPAMENTOS.REGIONAL => null
	EQUIPAMENTOS.TIPOEQ => null)] during the execution of the query was detected to be null.  Primary keys must not contain null.
Query: ResultSetMappingQuery(referenceClass=Equipamentos sql="select CONVERT(VARCHAR(10),DATA,103) as data, CONVERT(MONEY,((CAST(COUNT(SITUACAO) as float) - CAST(SUM(SITUACAO) as float))/CAST(COUNT(SITUACAO) as float)) * 100,0) as INDICE from EQUIPAMENTOS a join STATUS_EQUIPAMENTO b on a.STATUS_EQUIPAMENTO = b.ID_EQUIP where a.COMUNICACAO <> 1 and a.TIPOEQ BETWEEN 1 and 5 and  DATA BETWEEN '16-02-13' and '22-02-13' and  a.REGIONAL = 1GROUP BY b.DATA order by b.DATA ")
	at org.eclipse.persistence.exceptions.QueryException.nullPrimaryKeyInBuildingObject(QueryException.java:895)
	at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:584)
	at org.eclipse.persistence.queries.EntityResult.getValueFromRecord(EntityResult.java:192)
	at org.eclipse.persistence.queries.ResultSetMappingQuery.buildObjectsFromRecords(ResultSetMappingQuery.java:139)
	at org.eclipse.persistence.queries.ResultSetMappingQuery.executeDatabaseQuery(ResultSetMappingQuery.java:195)
	at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
	at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
	at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
	at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
	at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1463)
	at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:485)
	at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:742)
	at br.com.mda.controler.EquipamentosJpaController.calculeIndiceGprs(EquipamentosJpaController.java:322)
	at br.com.mda.bean.teste.main(teste.java:67)
Java Result: 1

Alguém sabe por quê?

Sds,

Maurício

Nao tentou fazer mais simples igual o exemplo que passei?

Cara,

Eu estou utilizando JPA para fazer as consultas. No exemplo ele mostra como fazer com o Hibernete. Pelo menos foi o que eu entendi...

Tem como fazer com JPA também??? Como faz a chamada???

Sds,

Maurício.

Cara,

Eu estou utilizando JPA para fazer as consultas. No exemplo ele mostra como fazer com o Hibernete. Pelo menos foi o que eu entendi...

Tem como fazer com JPA também??? Como faz a chamada???

Sds,

Maurício.[/quote]
Não trabalho com JPA. Como agora você já tem as chaves de busca, pode então pesquisar como se faz o mesmo para JPA. E você pode também seguir o link que te passaram, na página 8 tem exemplos de query nativa. Então primeiro pratique exemplos simples isolados para aprender e ver funcionando e depois implemente no seu projeto que terá mais segurança.