I am using JPA/Hibernate as ORM and now want to optimize my queries to only load necessary data for a specific endpoint. What's the best way to only load a subset of attributes of a specific class and then convert it to JSON? For the Endpoints I use Spring MVC and Jackson JSON Mapper.
Approaches I figured out, which I haven't tested yet.
Create POJO objects which only include the necessary attributes and map the Query fields with the attributes using
@SqlResultSetMapping.This approach requires adding a lot of additional classes, but other than that it seem good.
Ignore the overhead in the database queries and limit my response data with JSONViews.
This can get messy real fast, putting together the different JSONViews seems tedious. For most queries the overhead is definitely insignificant but I am curious how to map larger more complex queries.
Use Java.sql.PreparedStatements and map the ResultSet manually. Additionally use @JsonInclude(Include.NON_NULL) to only use non null values. For now this seems like the best solution to me, but it ignores JPA entirely and I am not sure if that should be my go to solution. I know I lose every advantage of an ORM, but it seems that every other solution needs similar or more complex work.
- ???
The last couple of month I predominantly developed in JavaScript/Node and I liked that I could exactly generate the objects I needed for the response. Is there a recommended way of doing such things, to me this seems like a common use case.
thanks