Search code examples
javahibernateprojection

How can i only get column which addScalar from DTO class?


I have a question about addScalar in Hibernate. Example I have DTO class:

public class FieldInfoDTO {
    private String fieldInfo1;
    private String fieldInfo2;
    private String fieldInfo3;
    private String fieldInfo4;
    private String fieldInfo5;
}

Then in DAO class I did this:

String sql = "SELECT field_info1 AS fieldInfo1 FROM tbl_field_info;"
SQLQuery query = getSession().createSQLQuery(sbQuery.toString());
query.addScalar("fieldInfo1", StringType.INSTANCE);
query.setResultTransformer(Transformers.aliasToBean(FieldInfoDTO.class));
return query.list();

I expect the result will be like this in Postman:

{
   "fieldInfo1" : "value"
}

But it return:

{
    "fieldInfo1" : "value",
    "fieldInfo2" : null,
    "fieldInfo3" : null,
    "fieldInfo4" : null,
    "fieldInfo5" : null
}

Is there any way to display only the column I addScalar?


Solution

  • I think the issue here is due to the statement :

    query.setResultTransformer(Transformers.aliasToBean(FieldInfoDTO.class));
    

    as it formats the result as per the attributes in FieldInfoDTO class(though the other fields gets set to null)

    Try removing it and fetch the result in list of String.