4

i have hibernate criteria with specific projection list:

criteria.setProjection(Projections.projectionList()
            .add(Projections.property("contract.autoId"), "contractId")
            .add(Projections.property("customer.firstName"), "firstName")
            .add(Projections.property("contract.startDate"), "startDate")
            .add(Projections.property("contract.endDate"), "endDate"));

I want to map the response of this criteria to the following DTO object:

public class Contract {
    private int contractId;
    private String description;
    private Date startDate;
    private Date endDate;
}

The types of response for this criteria:
enter image description here
So, first object has Long type, but in DTO contractId has int type.I don't have permission to change this dto object.
So, when i added ResultTransformer to my criteria:

criteria.setResultTransformer(Transformers.aliasToBean(Contract.class));

I got following exception:

java.lang.IllegalArgumentException: argument type mismatch

Is it possible to say to Transformers.aliasToBean to convert automatically value from Long type to int?

iChrome
  • 443
  • 1
  • 6
  • 24

1 Answers1

2

You can transform your type by using the addScalar method, which will take care of transforming your result to expected type. But afaik, it can only be done with Native Query. So you have first to convert your projection to a query, then add the scalar:

yourSession
    .createSQLQuery("select autoId, firstName, startDate, endDate from ...")
    .addScalar("contractId") //or you can specify the type with .addScalar("contractId", Hibernate.TheTypeYouWant)

Reference: https://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html/ch13.html

Leviand
  • 2,745
  • 4
  • 29
  • 43
  • 1
    ok, it's a solution. But i'm not a big fan of writing native sql queries. And i think it's better to create custom ResultTransformer and make proper type casting by hands. I just thought, that maybe there is some way to do it automatically. – iChrome Sep 27 '18 at 13:46
  • me neither, but if is a "one shot" query you can achieve you result faster then creating a custom ResultTransformer , but I agree with you! One of the many possible solutions ;) . Glad it helped – Leviand Sep 27 '18 at 14:00