JPA Entity that has a OneToMany relationship and want to use DTO

Tags: , , , ,



I have an entity called “Review” that has a OneToOne relationship with a “User” entity and a OneToMany relationship with a “ReviewStage” entity. I have implemented a DTO pattern so, I also have ReviewDTO which is actually what is being sent to the UI. I am using mapstruct to map the entity to dto. All is working well however, I would rather use the UserDTO and ReviewStageDTO in the relationship mappings.

This works well:

@Entity
@Getter @Setter @NoArgsConstructor
public class Review {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long reviewId;
    
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "ownerId")
    private User owner;

    @OneToMany(mappedBy = "reviewId")
    private Set<ReviewStage> stages;

}

For fun, I tried this but, obviously doesn’t work:

@Entity
@Getter @Setter @NoArgsConstructor
public class Review {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long reviewId;
    
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "ownerId")
    private UserDTO owner;

    @OneToMany(mappedBy = "reviewId")
    private Set<ReviewStageDTO> stages;

}

I just need a nudge in the right direction. Thanks,

Answer

The relationships should be between entities only and if you want to make a dto for Review and inside this dto you want to return the UserDto for example you should create a mapstruct class to map between UserEntity to UserDTO

Example

class UserDto {
    /// put any fields here that you want to map
}

class ReviewDto {
    UserDto user;
}

@Mapper(componentModel = "spring")
class UserMapper {
    UserDto map(User user);
}

@Mapper(componentModel = "spring", uses={UserMapper.class})
class ReviewMapper {
    ReviewDto map(Review review);
}


Source: stackoverflow