I have an issue with Mapstruct mapping my entities in a Spring-Boot rest api with One-To-Many and Many-To-One relationship.
I use
mapstruct 1.4.2.Final,
Lombok 1.18.20
I have the classes below
Policy.class
@Data
@Entity
@Table(name = "Policy")
public class Policy implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "Policy_UID", nullable = false)
private Integer policyUid;
//other fields without relationships
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "userID", referencedColumnName = "Id")
private User user;
}
User.class
@Data
@Entity
@Table(name = "User")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "Id")
private Integer id;
//other fields without relationships
@OneToMany(mappedBy = "user")
@JsonIgnore
public List<Policy> policyList;
}
PolicyDTO.class
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PolicyDTO {
private Integer policyUid;
//other fields without relationships
private UserDTO user;
}
UserDTO.class
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDTO {
private Integer id;
//other fields without relationships
public List<PolicyDTO> policyList;
}
PolicyMapper.class
@Mapper (componentModel = "spring")
public interface PolicyMapper {
PolicyDTO policytoPolicyDTO(Policy policy);
List<PolicyDTO> toPolicyListDTO(List<Policy> policies);
}
UserMapper.class
@Mapper(componentModel = "spring")
public interface UserMapper {
UserDTO toUserDTO(User user);
List<UserDTO> toUserListDTO(List<User> UsersList);
}
and the calling for results
List<PolicyDTO> list = policyMapper.toPolicyListDTO(paging.getContent());
return new PageImpl<>(list, page, paging.getTotalElements());
So when I put in comment the private UserDTO user; into PolicyDTO and public List policyList; into UserDTO
The result Policies list it's ok with values in all fields except the two commented of course. If I uncomment the two fields into DTO's with the bidirectional relationship the result is null not only in relationship fields but in all fields. all fields are null like no results at all behavior.
So the problem is with bidirectional one-to-many and many-to-one relationship mapping.
In addition to this, I have to say for your info that most Policies have null UserID if it matters.
Does anyone have any suggestions on this issue?
Thank you in advance