Skip to content
Advertisement

Populate DTO using query with JOIN

I have this main Product table:

Additional table for storing categories that should be returned as List:

Additional table for storing Payment Methods that should be returned as List:

I want to return a result like this:

I tried this:

What is the proper way to populate this DTO?

Advertisement

Answer

If, as indicated in your comments, you need query your information with HQL a good way to proceed can be the following.

First, modify your Product entity an include relationships for both ProductCategory and ProductPaymentMethods, something like:

Modify both ProductCategory and ProductPaymentMethods to accommodate the entities relationship:

With this setup, as you can see in the Hibernate documentation – it is for an old Hibernate version, but it is correct today, you can use fetch joins to obtain the required information:

A “fetch” join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection.

For your example, consider the following HQL (assume outer join semantics, modify it as appropriate):

This will provide you the list of products for userId 1, with all the associated references to categories and payment methods initialized.

The conversion between the entity and the DTO should be straightforward:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement