I wonder if it's possible (and if it's the good method) to map sql result of native query in pojo with other pojos in its attributes. I'm searching something like that :
ResultPojo Class
public class ResultPojo {
private MyPojo myPojo;
private Integer firstSimpleAttribute;
private Integer secondSimpleAttribute;
private Double thirdSimpleAttribute;
// Empty Constructor + Constructor with fields + Getter + Setter
}
MyPojo Class
public class MyPojo {
private Long id;
private String label;
private MySubPojo mySubPojo;
// Empty Constructor + Constructor with fields + Getter + Setter
}
MySubPojo Class
public class MySubPojo {
private String text;
// Empty Constructor + Constructor with fields + Getter + Setter
}
Mapping part
@SqlResultSetMapping(
name = "CustomMapping",
classes={
@ConstructorResult(
targetClass=MyPojo.class,
columns={
@ColumnResult(name="id", type=Long.class),
@ColumnResult(name="label", type=String.class),
@ColumnResult(name="mySubPojo", type=MySubPojo.class)
}
)
},
columns = {
@ColumnResult(name = "firstSimpleAttribute", type = Integer.class),
@ColumnResult(name = "secondSimpleAttribute", type = Integer.class),
@ColumnResult(name = "thirdSimpleAttribute", type = Double.class)
}
)
Native Query
Query query = this.entityManager.createNativeQuery(
"SELECT r.*, me.id, me.label, mse.*
FROM result r
INNER JOIN my_entity me ON r.id_my_entity = me.id_my_entity
INNER JOIN my_sub_entity mse ON me.id_my_sub_entity = mse.id_my_sub_entity",
"CustomMapping");
List<Object[]> result = query.getResultList();
// Convert Object[] to List<ResultPojo>
When I do that, I obtain a NullPointerException
due to line @ColumnResult(name="mySubPojo", type=MySubPojo.class)
. Is there a way to manage this kind of mapping?