I’ve simply stumbled upon this nice submit by Vlad Mihalcea, titled The Finest Technique 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 rapidly present the second greatest means of doing the identical, with jOOQ this time.
Tip: you may 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 submit, which initiatives issues into this kind hierarchy:
public report PostCommentDTO (
Lengthy id,
String overview
) {}
public report PostDTO (
Lengthy id,
String title,
Listing<PostCommentDTO> feedback
) {}
So, we’ll be utilizing jOOQ like this utilizing the MULTISET
worth constructor:
Listing<PostDTO> end result =
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 perform, if that’s extra your factor (and should you’re not nesting collections greater than 1 degree deep):
Listing<PostDTO> end result =
ctx.choose(
POST_COMMENT.submit().ID,
POST_COMMENT.submit().TITLE,
multisetAgg(POST_COMMENT.ID, POST_COMMENT.REVIEW)
.convertFrom(r -> r.map(mapping(PostCommentDTO::new)))
.from(POST_COMMENT)
.the place(POST_COMMENT.submit().TITLE.like(postTitle))
.fetch(mapping(PostDTO::new));
Each options are fully sort protected, utilizing ad-hoc report conversion. You alter the schema, re-generate the code, and your code now not compiles.
Other than the question itself, you don’t want to write down any extra infrastructure logic.
Cool, proper? 🙂