mapstruct中的映射循环问题

Mapping circular issue in mapstruct

假设我有下一个实体:

public class Profile {

   private UUID id;
   //Other properties

   private ProfileUser user;

   //Getters and Setters of properties
}

public class ProfileUser {

    private String username, password;

    private UUID id;
    private String firstName, lastName;
    //Other properties

    private Set<Group> groups;
    private Set<Authority> authorities;
    private Profile profile;

    //Getters and Setters
}

public class Group {

    private String name;

    private Collection<ProfileUser> users;
    private Collection<Authority> authorities;

    //Getters and Setters
}

public class Authority {

    private String name;

    private Collection<ProfileUser> users;
    private Collection<Group> groups;

    //Getters and Setters
}

我需要将其映射到下一个 DTO:

public class ProfileServiceDTO {

    private UUID id;
    //Other properties

    private ProfileUserServiceDTO user;

    //Getters and Setters
}

public class ProfileUserServiceDTO implements Serializable {
    private static final long serialVersionUID = 1L;

    private String username, password;

    private UUID id;
    private String firstName, lastName;
    //Other properties

    private Set<GroupServiceDTO> groups;
    private Set<AuthorityServiceDTO> authorities;

    //Getters and Setters
}

public class GroupServiceDTO {

    private String name;

    private Set<ProfileUserServiceDTO> users;
    private Set<AuthorityServiceDTO> authorities;
}

public class AuthorityServiceDTO implements Serializable {
     private static final long serialVersionUID = 1L;

     private String name;

     private Set<GroupServiceDTO> groups;
     private Set<ProfileUserServiceDTO> users;

     //Getters and setters
}

我需要将实体映射到 DTO,但要避免循环,

我如何以正确的方式执行此操作,以便我可以在配置文件 DTO 下看到 ProfileUser DTO 及其组和权限??

现在我在配置文件映射器中使用下一个代码:

@Mapping(target = "user.groups", expression = "java(null)")
@Mapping(target = "user.authorities", expression = "java(null)")
public ProfileServiceDTO profileToProfileServiceDTO(Profile profile);

但上面的映射代码没有 return 组和权限,因为我将其设置为 null 以避免循环,那么我该如何解决这个问题?

我通过使用解决了它:

@Mapping(source = "user.groups", target = "user.groups", qualifiedByName = "profileAndGroup")
@Mapping(source = "user.authorities", target = "user.authorities", qualifiedByName = "profileAndAuthority")
public ProfileServiceDTO profileToProfileServiceDTO(Profile profile);

@Named("profileAndGroup")
@Mapping(target = "users", expression = "java(null)")
@Mapping(target = "authorities", expression = "java(null)")
GroupServiceDTO profileAndGroup(Group group);

@Named("profileAndAuthority")
@Mapping(target = "users", expression = "java(null)")
@Mapping(target = "groups", expression = "java(null)")
AuthorityServiceDTO profileAndAuthority(Authority authority);