Hibernate - createNativeQuery with the result "non-entity class"

I am new to all Hibernate / JPA stuff, so I will try to be as clear as possible.

Is there a way in Hibernate to use createNativeQuery to select one or more fields in a query without using the Entity class as the return object?

I am trying to do this without using any XML related material.

Query query = getEntityManager().createNativeQuery("select name from contact where id_contact = :idContact", String.class);
query.setParameter("idContact", 9293L);
Object string = query.getSingleResult();
System.out.println(string);

Using this, I have an Exception: Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.MappingException: Unknown entity: java.lang.String

thanks

Edit:

I also tried:

Query query = getEntityManager().createNativeQuery("select name from contact where id_contact = :idContact");
query.setParameter("idContact", 9293L);
List list = query.getResultList();
if (!list.isEmpty()){ 
    Object string = list.get(0);
    System.out.println(string);
}

With the same Exception: Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object;

Edit (2): I'm starting to think that this is either a bug in Hibernate, or it is impossible to do such things ...

+4
source share
5 answers

, String.class createNativeQuery. String.class . , String , .

, , createNativeQuery, .

String SQL = ".."; //same SQL as you had before
Query query = getEntityManager().createNativeQuery(SQL); //no entity mapping
query.setParameter("idContact", 9293L);
Object string = query.getSingleResult();
System.out.println(string);
+9

jpql EntityManager .

.

 List<Object[]> listResults = query.getResultList();

: -

for (Object[] record : listResults) {

            //Iterate Logic will come here

                    }
+5

Just try calling createNativeQuery()without going through String.class. If the column namehas a string type in the database query.getSingleResult(), it will actually return String.

+2
source

to try

Query query = getEntityManager().createNativeQuery("select name from contact where id_contact = :idContact", String.class);
query.setParameter("idContact", 9293L);
List list = query.getResultList();
if (!list.isEmpty()){ 
    Object string = list.get(0);
    System.out.println(string);
}

In Review

http://sysout.be/2011/03/09/why-you-should-never-use-getsingleresult-in-jpa

0
source
String SQL = ".."; //same SQL as you had before
Query query = getEntityManager().createNativeQuery(SQL); //no entity mapping
query.setParameter("idContact", 9293L);
String string = (String)query.getSingleResult();
System.out.println(string);
0
source

All Articles