Search code examples
javaspring-bootmapstruct

How do I map the User model inside the model with the mapper?


How do I map the user object in my UserRole model to the User model?

UserRole Model:

public class UserRole extends Base {
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "user_id"  ,referencedColumnName = "id")
        User user;
        @JoinColumn(name = "role_id"  ,referencedColumnName = "id")
        @ManyToOne(fetch = FetchType.LAZY)
        Role role;
        @Column(name ="is_active")
        Boolean isActive;
}

User Model:

public class User extends Base {
    @Column(name = "name")
    String name;
    @Column(name = "surname")
    String surname;
    @Column(name = "email", unique = true)
    String email;
    @Column(name = "password")
    String password;
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "user_role", 
            joinColumns = @JoinColumn(name = "user_id"), 
            inverseJoinColumns = @JoinColumn(name = "role_id") 
    )
    List<Role> roles;
    @Column(name = "status")
    @Enumerated(EnumType.STRING)
    Status status;
}

I did this with mapper but it didn't work

@Mapping(target = "id", source = "user.id")
    @Mapping(target = "name", source = "user.name")
    @Mapping(target = "surname", source = "user.surname")
    @Mapping(target = "email", source = "user.email")
    @Mapping(target = "roles", source = "user.roles")
    List<User> toDtoList(List<UserRole> userRoles);
  • The extended Base model contains only id, created_at, and updated_at columns.

Solution

  • I think the method used is not quite right for mapping a list of UserRole to list of User objects.

    @Mapping(target = "") annotation is used to map individual objects and not collections. So, we can use the below to resolve the issue.

    1. Create a method(toUser) that maps UserRole to User objects with individual field mappings.
    2. Create another method(toUserList) to handle the list conversion, here the MapStruct will reuse the logic present in the toUser method for each element in the list.

    Updated code,

    @Mapping(target = "id", source = "user.id")
    @Mapping(target = "name", source = "user.name")
    @Mapping(target = "surname", source = "user.surname")
    @Mapping(target = "email", source = "user.email")
    @Mapping(target = "roles", source = "user.roles")
    User toUser(UserRole userRole);
    
    List<User> toUserList(List<UserRole> userRoles);