Pregunta

I have created a native query

Query q=em.createNativeQuery("select *\n" +
    "from contaarticoli ca,articolo a\n" +
    "where ca.articolo=a.id\n" +
    "order by ca.qta desc\n" +
    "limit 1;");

In workbench i have created a view :

create view contaarticoli(articolo,qta)as
(
 select a.idarticolo as articolo,sum(a.quantita) as qta
 from articoliordine a
 group by a.idarticolo
);

When I do:

List<Object> lista=q.getResultList();
System.out.println(lista.get(0))

In output i have : [Ljava.lang.Object;@1c5b8a4

Why?

¿Fue útil?

Solución 2

Native queries executed with Query result and Object always until you define the resultClass property in the createNativeQuery method.

 createNativeQuery

Query createNativeQuery(java.lang.String sqlString,
                        java.lang.Class resultClass)

    Create an instance of Query for executing a native SQL query.

    Parameters:
        sqlString - a native SQL query string
        resultClass - the class of the resulting instance(s) 

If you have a entity with the same name of the result fields of the query, add resultClass=Class.class and will create objects automatically

Are you are using a join between 2 tables, you can use @SqlResultSetMapping as it follows.

@SqlResultSetMapping(name="ScalarAndEntities",
    entities={
        @EntityResult(name="org.hibernate.test.annotations.query.Night", fields = {
            @FieldResult(name="id", column="nid"),
            @FieldResult(name="duration", column="night_duration"),
            @FieldResult(name="date", column="night_date"),
            @FieldResult(name="area", column="area_id")
        }),
        @EntityResult(name="org.hibernate.test.annotations.query.Area", fields = {
            @FieldResult(name="id", column="aid"),
            @FieldResult(name="name", column="name")
        })
    },
    columns={
        @ColumnResult(name="durationInSec")
    }
)

Use with

Query q = entityManager.createNativeQuery(sqlQuery, "ScalarAndEntities");

Read more about how to retrieve entities from nativequeries here ,

Otros consejos

Because you get back a List<Object[]>. Each array has the same number of columns, corresponding to the query columns.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top