I got the results using JPA Query like below:
String query = "Select dataId, dataName, dataValue, datadesc From Data";
Query q = entityManager.createQuery(query).setMaxResults(10);
List<Object[]> dataList = q.getResultList();
Please not that, I don't want to select all fields like "Select d From Data d". I will select fields like following: "dataId, dataName", "dataId, dataName, datadesc "
I need to loop through dataList above and typecast each element based on field type:
My Data entity class like below:
public class Data{
private Long permitId;
private String permitNumber;
private Date permitDate;
}
I did casting as below:
for (Object[] object : dataList) {
Data d = new Data();
d.setDataId((Long)object[0]);
d.setDataName((String)object[1]);
...
}
But I would like to do this casting as dynamic:
for (Object[] object : dataList) {
Data d = new Data();
**for (Field field : Data.class.getDeclaredFields()) {
if (field.getName().equals("dataId")) {
d.setDataId(**(field.getType())**object[0]);
}
if (field.getName().equals("dataName")) {
d.setDataName(**(field.getType())**object[1]);
}**
...
}
Is there anyway to achieve this ?
Aucun commentaire:
Enregistrer un commentaire