Java how to do a native query and return to a DTO list

Asked

Viewed 2,863 times

2

I am using Spring Hibernate and am trying to make a native query with Join back to a DTO list. I tried using @Query(value="", nativeQuery=true) with a List but it returns the serialized attributes. I also tried with @Sqlresultsetmapping inside DTO, but I don’t think that would be the most performative way.

  • I was able to solve using Rowmapper<T>

1 answer

1


Look for result Transformer. They were made exactly for do what you want and works with HQL and SQL (Native query)

https://stackoverflow.com/a/13782489/2387977

If you can’t, for some reason, there’s another way:

List resultado = s.createSQLQuery(
  "SELECT new SeuDto(st.name, st.age) FROM Student st ";

In which you can make one new of the direct object in the select and receive as a result an Object[] list that will be instances of "Seudto". This works as long as you have a constructor in "Seudto" accepting these parameters name and age, in the case of the example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.