1

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.

  1. 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.

  2. 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.

  3. 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.

  4. ???

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

1

1 Answer 1

1

We always used POJO object for these needs before, but sometime it's more suitable to use 'select new' construction than result mapping.

select new com.example.MyClass(id, ...) From MyObject

Maybe you can consider that.

Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know this existed, works great. Sure if I want to do more with the object I will create a POJO, but most of my endpoints directly return the object. I am going to let the question open for a day or so, if someone wants to add anything, but I will except your answer in the next days.
And yes, if you just want to limit amount of attributes you can create another constructor for your mapped object and use this 'select new' approach without creating additional POJO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.