3

My old Hibernate-only code uses something like

session.createSQLQuery("SELECT * FROM CATS")
.addScalar("ID", Hibernate.LONG)
.addScalar("NAME", Hibernate.STRING)
.addScalar("BIRTHDATE", Hibernate.DATE)

In the new project we use Hibernate EntityManager (the JPA implementation).

Is there an equivalent to those calls to addScalar()? Do I need to specify the types of the returned columns as I did before?

For example, if I don't use addScalar will the SQL query results be cached?

muriloq
  • 2,692
  • 5
  • 29
  • 32

3 Answers3

2

I know its a pretty old question, just answering it in case someone else faces the problem

createNativeQuery takes a parameter which specifies the type of class the result is obtained, So in your case , you can change it to,

val sql = "select distinct story as story from ...";
Query = getEntityManager().createNativeQuery(sql,Story.class);
  • This could be nice, but doesn't seem to work on primitives / scalars (e.g - Short.class for example), any idea why? (Unknown entity: java.lang.Short) – JRun Dec 24 '15 at 08:05
  • Put primitives to a DTO class. – kinjelom Aug 10 '17 at 09:45
  • It worked perfectly mentioned that my DTO has Enum + Custom Serializer/Deserializer. I tried 4 different ways but non of these worked when this solution is simple and working. – MD TAREQ HASSAN Jan 29 '19 at 04:22
  • Mentioned that It worked mentioned that I used `@Entity` Annotation for DTO just to make it work because I tried 4 different ways but non of these worked when this solution is simple and working (with trick `@Entity` Annotation for DTO) – MD TAREQ HASSAN Jan 29 '19 at 04:31
2

The post Hibernate native query - char(3) column

seems to offer a similar, shorter solution, which appears to work for me:

Query q2 = em.createNativeQuery("select sc_cur_code, sc_amount from sector_costs");
q2.unwrap(SQLQuery.class).addScalar("sc_cur_code", StringType.INSTANCE);
Community
  • 1
  • 1
Ben Kirby
  • 904
  • 2
  • 11
  • 29
1

I was looking for the exact same thing and couldn't find anything in JPA.

Wow, 6 months and not answer :)

Don't know if it helps or not, but I've found a workaround:

The tick is that you cannot cast directly to SQLQuery, you have to cast to HibernateQuery, then call getHibernateQuery, then cast the result to SQLQuery.

And now for some (scala) code:

val sql = "select distinct story as story from ...";
val q: Query = getEntityManager().createNativeQuery(sql);
//hello nasty hack
q.asInstanceOf[HibernateQuery].getHibernateQuery().asInstanceOf[SQLQuery].addScalar("story", StandardBasicTypes.LONG);
//next, caching  
q.setHint("org.hibernate.cacheable", true);
q.setHint("org.hibernate.cacheRegion", "query.getTopLinks");

ugly but it does the job :)