If you use JPA / Hibernate to execute SQL queries, you are using the wrong tool. Hibernate is an ORM, and you must display tables for objects. This is the whole point of JPA. I just want to execute SQL queries, use JDBC (and Spring JdbcTemplate, for example)
After tables1 and table2 are compared with entities (let them access these objects T1 and T2), you will no longer need these SQL queries, since JPQL can select only some fields of objects. Your request may look like this (depending on the relationship between t1 and t2):
select t1.col1, t2.col5 from T1 t1 join t1.t2 t2
And you just need to iterate over the result (Object [] list) to create your results (which is a DTO, not a mapped entity):
List<Object[]> rows = (List<Object[]>) query.list(); List<Result> listOfResults = new ArrayList<Result>(rows.size); for (Object[] row : rows) { listOfResults.add(new Result((String) row[0], (String) row[1])); }
source share