I am using JPA in my project.
I came to a query in which I need to make join operation on five tables. So I created a native query which returns five fields.
First declare following annotations:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface NativeQueryResultEntity {
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NativeQueryResultColumn {
int index();
}
Then annotate your POJO as follows:
@NativeQueryResultEntity
public class ClassX {
@NativeQueryResultColumn(index=0)
private String a;
@NativeQueryResultColumn(index=1)
private String b;
}
Then write annotation processor:
public class NativeQueryResultsMapper {
private static Logger log = LoggerFactory.getLogger(NativeQueryResultsMapper.class);
public static List map(List
Use above framework as follows:
String sql = "select a,b from x order by a";
Query q = entityManager.createNativeQuery(sql);
List results = NativeQueryResultsMapper.map(q.getResultList(), ClassX.class);