I haven't been able to find any specific solutions:
I have a Native Query in Spring Data, and need to map the resultset to a custom data bean object.
@Query(query = "select id as activityId, activity_title as activityTitle,
activity_instructions as activityInstructions from activities_t " +
"where case when activity_code ~ '^\\d+$' " + // Digits only
" then cast(activity_code as int) between :firstId and :lastActivityId end",
resultSetMapping="myQueryResultSet",
name = "myQuery")
public List<Activity> findActivities(@Param("firstId") int firstId, @Param("lastId") int lastId);
The problem is, this needs to return a custom object, Activity
, rather than the @Entity object ActivitiesT
.
Activity
is a custom POJO that has a subset of ActivitiesT
's fields, and some of the columns are slightly differently named:
Activity.java, 3 fields with getters/setters
activityId (ACTIVITIES_T.ID) <-- this is differently-named
activityTitle (ACTIVITIES_T.ACTIVITY_TITLE) <-- same name
activityInstructions (ACTIVITIES_T.ACTIVITY_INSTRUCTIONS) <-- same name
I found one solution here, but it doesn't work for me because I have a differently-named alias: Spring Data JPA map the native query result to Non-Entity POJO
Their solution is to use
@SqlResultSetMapping(
name="groupDetailsMapping",
classes={
@ConstructorResult(
targetClass=GroupDetails.class,
columns={
@ColumnResult(name="GROUP_ID"),
@ColumnResult(name="USER_ID")
}
)
}
)
They assume in the answer that all the columns in the custom POJO are named the same as in the expected @Entity object. For me that's not the case. Also, I can't put a SqlResultSetMapping on my Spring Data JPA Repository method.
Any solutions to this?