Spring boot setResultTransformer and addScalar

Viewed 5951

I have problem on returning query result set using entityManager object . I want to return my join query which should convert into pojo object.

so after many tries I found the below working code

public List<Test> getData() {

    Query a = entityManager.createNativeQuery("select t1.data1,t2.data2 from test1 t1 join test2 t2 on t1.id = t2.id");          
    a.unwrap(SQLQuery.class)      
    .addScalar("data1", LongType.INSTANCE)      
    .addScalar("data2", DoubleType.INSTANCE)      
    .setResultTransformer(Transformers.aliasToBean(Test.class));     

    return a.getResultList();    
}

But I had warnings that setResultTransformer() and addScalar() methods are deprecated.
Can any one please put the alternative code of it or please provide the solution.
Thanks.

1 Answers

1) The first thing deprecated is SQLQuery :

(since 5.2) use NativeQuery instead.

2) But it will not solve your issue because SQLQuery.addScalar() org.hibernate.query.Query.setResultTransformer() are also deprecated as you noticed.
From the Hibernate 5.3 migration guide :

With a ResultTransformer it is possible to define how the results of a query should be handled, i.e., it can be used to change the "shape" of the query results.

In Hibernate 6.0, the ResultTransformer will be replaced by a @FunctionalInterface and for this reason, the setResultTransformer() method in org.hibernate.query.Query is deprecated.

There is no replacement for ResultTransformer in Hibernate 5.3, therefore as recommended here, for the moment it can be used as-is.

So you can leave it such as and suppress the warning by adding also a TODO comment.

@SuppressWarnings("deprecation")
public List<Test> getData() {

    Query a = entityManager.createNativeQuery(
            "select t1.data1,t2.data2 >from test1 t1 join test2 t2 on t1.id = t2.id");
    a.unwrap(NativeQuery.class)
      // TODO warning to remove with Hibernate 6 for addScalar()
     .addScalar("data1", LongType.INSTANCE)
     .addScalar("data2", DoubleType.INSTANCE)
      // TODO warning to remove with Hibernate 6 for setResultTransformer()
     .setResultTransformer(Transformers.aliasToBean(Test.class));

    return a.getResultList();
}
Related