springhibernateormdtoobject-model

Retrieving foreign key attributes in DTO


I am using java+Spring framework+Hibernate for creating rest api but I have stumbled upon retrieving details of a table using foreign key attributes. I have the following tables::

https://i.sstatic.net/lG7UR.png

I am retrieving all the ratings given using product id and then mapping to DTO, now I also want to populate the username using idusers as this is my foreign key.

Same is the case when I try to retrieve ratings given by the users, instead of displaying idproducts I want to display the product name and product description as It is a foreign key.

Any advice on how to do so using DTO's.


Solution

  • You can use ModelMapper when converting a DTO to an Entity bean and back from Entity bean to a DTO.

    Add ModelMapper to your project

    <dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>2.3.5</version>
    </dependency>
    

    Define the ModelMapper bean in your Spring configuration

    @Bean
    public ModelMapper modelMapper() {
    return new ModelMapper();
    }
    

    Assuming the following models based on the given ER diagram you have given

    public class UserDto {
    Integer userId;
    String role;
    String username;
    String password;
    boolean enabled;
    ...default and parameterized constructor
    ...getter and setter methods
    }
    
    
    public class ProductDto {
    Integer productId;
    String imageUrl;
    String category;
    int productPrice;
    int productQuantity;
    String productName;
    String productDesc;
    ...default and parameterized constructor
    ...getter and setter methods
    }
    
    
    public class RatingDto {
    @Id
    Integer id;
    int rating;
    String review;
    String ratingscol;
    ProductDto productDto;
    UserDto userDto;
    ...default and parameterized constructor
    ...getter and setter methods
    }
    

    You can retrieve the ratings of a product using product id along with the user details by using the following method

     @Repository
     public interface RatingRepository extends JpaRepository<Rating, Integer>{
     List<Rating> findByProduct_ProductId(Integer productId);
     }
    

    Then mapping rating objects to DTO

     RatingDto ratingDto = modelMapper.map(rating, RatingDto.class);
    

    Now you can retrieve username as following

     ratingsDto.getUserDto().getUserName()
    

    The same way you can retrieve the ratings by userId and access product details