Tuesday, August 30, 2022
HomeProgrammingThe Second Greatest Solution to Fetch a Spring Information JPA DTO Projection...

The Second Greatest Solution to Fetch a Spring Information JPA DTO Projection – Java, SQL and jOOQ.


I’ve simply stumbled upon this nice put up by Vlad Mihalcea, titled The Greatest Solution to Fetch a Spring Information JPA DTO Projection. It bought some good traction on reddit, too. That is such a pleasant use-case and apt resolution, I needed to shortly present the second finest means of doing the identical, with jOOQ this time.

Tip: you possibly can simply use jOOQ with Spring Information JPA, simply use Spring Boot’s jOOQ starter, inject the DataSource to jOOQ, then delegate all repository queries to jOOQ.

I’ll skip proper to the hierarchical DTO projection from the put up, which tasks issues into this kind hierarchy:

public report PostCommentDTO (
    Lengthy id,
    String assessment
) {}

public report PostDTO (
    Lengthy id,
    String title,
    Checklist<PostCommentDTO> feedback
) {}

So, we’ll be utilizing jOOQ like this utilizing the MULTISET worth constructor:

Checklist<PostDTO> consequence =
ctx.choose(
        POST.ID,
        POST.TITLE,
        multiset(
            choose(POST_COMMENT.ID, POST_COMMENT.REVIEW)
            .from(POST_COMMENT)
            .the place(POST_COMMENT.POST_ID.eq(POST.ID))
        ).convertFrom(r -> r.map(mapping(PostCommentDTO::new)))
   )
   .from(POST)
   .the place(POST.TITLE.like(postTitle))
   .fetch(mapping(PostDTO::new));

Alternatively, use the MULTISET_AGG mixture operate, if that’s extra your factor (and in the event you’re not nesting collections greater than 1 stage deep):

Checklist<PostDTO> consequence =
ctx.choose(
        POST_COMMENT.put up().ID,
        POST_COMMENT.put up().TITLE,
        multisetAgg(POST_COMMENT.ID, POST_COMMENT.REVIEW)
            .convertFrom(r -> r.map(mapping(PostCommentDTO::new)))
   .from(POST_COMMENT)
   .the place(POST_COMMENT.put up().TITLE.like(postTitle))
   .fetch(mapping(PostDTO::new));

Each options are utterly sort protected, utilizing ad-hoc report conversion. You modify the schema, re-generate the code, and your code now not compiles.

Aside from the question itself, you don’t want to put in writing any further infrastructure logic.

Cool, proper? 🙂

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments