Native Query Result Parameter is Not mapped to Class Modal

609 views Asked by At

I have using the Native Query in JPA Repository and my query is as:

select u.*, max(a.version_no) as versionNo from users u left join andother_table a on u.id=a.user_id  where u.title='abc' group by id;

from my Query i get the "versionNo" which is not mapped to mu user modal.I have put this also in our user modal like as

@Transient
private String versionNo;

with is getter/setter.but in view i will get versionNo is null.

Please help me.

1

There are 1 answers

1
Predrag Maric On

It is null because you annotated it as @Transient, so it is not populated with DB values. You can execute the query without mapping the results directly to your class, and populate the class manually (the query will return a list of Object[]). Other than this, I'm not aware of any alternatives (because of @Transient).

List<Object[]> results = session.createNativeQuery("select max(a.version_no) as versionNo, u.* from users u left join andother_table a on u.id=a.user_id  where u.title='abc' group by id").list();
List<MyClass> myClasses = new ArrayList<MyClass>();
for (Object[] result : results) {
    MyClass mc = new MyClass();
    ...
    mc.setVersionNo(result[0]);
    mc.setSomethingElse(result[1])
    ...
    myClasses.add(mc);
}

Each entry in results list is an object array representing a row returned by native query. Columns are ordered as you select them, so if you put versionNo in the first place in SELECT clause, it will be available with result[0].