I am quite new to Hibernate. I am using it along-with my Spring Boot project. I want to write native SQL Queries due to the complex joins involved. On execution of the queries the values returned is in the form of a list and there is no simple way to map them to a HashMap.
Right now I am using the below approach which works but is heavily dependent on the sequence of the values returned from the query list.
Is there any simple and efficient way to map this result.
DAO
@Transactional
public List<Object> getAllUsers() {
Session currentSession = entityManager.unwrap(Session.class);
String queryString = "select ts.id as id, ts.remarks, concat(s.first_name, ' ',s.last_name) as studentName,\n" +
"ts.start_date as startDate, ts.end_date as endDate, ts.status,\n" +
"ts.created_at as createdAt, ts.created_by as createdBy, \n" +
"ts.updated_at as updatedAt, ts.updated_by as updatedBy\n" +
"from TRN_STATUS ts join types lt on ts.type_id = lt.id join users s on s.id = ts.id \n" +
"join category ct on ts.cat_id = ct.id\n" +
"where ts.tenant_id = 1";
NativeQuery query = currentSession.createNativeQuery(queryString);
List<Object> result = (List<Object>) query.getResultList();
currentSession.close();
return result;
}
Service
public List<Map<String, Object>> getCount(Optional<String> userId, String userType, String limit, String offset) {
List<Object> users= userDAO. getAllUsers();
List<Map<String, Object>> userList = new ArrayList<>();
Iterator userItr = users.iterator();
ObjectMapper userMapper = new ObjectMapper();
Map<String, Object> map;
UserModel obj = new UserModel();
while(userItr.hasNext()) {
Object[] resobj = (Object[]) leaveItr.next();
obj.setId(String.valueOf(resobj[0]));
obj.setStartDate(String.valueOf(resobj[1]));
obj.setEndDate(String.valueOf(resobj[2]));
obj.setDescription(String.valueOf(resobj[3]));
obj.setLeaveType(String.valueOf(resobj[4]));
obj.setCategoryId(String.valueOf(resobj[5]));
obj.setCategoryName(String.valueOf(resobj[6]));
obj.setStatus(String.valueOf(resobj[7]));
obj.setDesignation(String.valueOf(resobj[8]));
obj.setActionBy(String.valueOf(resobj[9]));
obj.setStudentName(String.valueOf(resobj[10]));
obj.setImgUrl(String.valueOf(resobj[11]));
map = userMapper.convertValue(obj, Map.class);
userList.add(map);
logger.info("Value displayed was: "+ map);
}
return userList;
}
UserModel
import lombok.Data;
public @Data class UserModel {
private String id;
private String startDate;
private String endDate;
private String description;
private String leaveType;
private String categoryId;
private String categoryName;
private String status;
private String designation;
private String actionBy;
private String studentName;
private String imgUrl;
private String createdDate;
private String hostelName;
private String blockName;
private String roomName;
}