如何使用模型映射器将2个类映射到Dto

时间:2018-07-24 11:04:52

标签: java spring spring-boot modelmapper

我想使用模型映射器转换两个具有相同属性的对象。由于多对多的关系,我多么无法。

private User fromEntity(UserEntity userEntity) {
LOGGER.info("Converting userEntity to user model with Id" + 
userEntity.getUserId());
User user = modelMapper.map(userEntity,User.class);
LOGGER.info("Converted userEntity to user model with Id" + 
userEntity.getUserId());
return user;
}

我有User和UserEntity类。它们与Role和RoleEntity类映射:

这是我的用户类别:

public class User {

    private Long userId;


    private String userUsername;
    private String userName;
    private String userSurname;
    private String password;
    private String addres;
    private String eMail;
    private boolean active = false;

    private String key;
    //@JsonBackReference
    private Set<Role> role ;


    public User(){
        role = new HashSet<>();

    }

角色类别:

  public class Role {

private Long roleId;

    private String role;

    private Set<User> user;

    public Role(){
        user = new HashSet<>();
    }

    //@JsonManagedReference
    public Set<User> getUser() {
        return user;
    }
    }

UserEntity类:

@Entity
@Table( name="users" )
public class UserEntity {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "userId")
    private Long userId;

    private String userUsername;
    private String userName;
    private String userSurname;
    private String password;

    private String addres;

    private String eMail;

    private boolean active;

    private String key;


    @JsonManagedReference
    @ManyToMany( cascade = CascadeType.ALL, fetch = FetchType.EAGER )
    @JoinTable(
            name = "users_roles",
            joinColumns = {@JoinColumn(name="userId")},
            inverseJoinColumns = {@JoinColumn(name="roleId")}
    )
    private Set<RoleEntity> roleEntities;

    public UserEntity(){
        active=false;
        roleEntities = new HashSet<>();

    }

和RoleEntity类:

@Entity
@Table(name="roles")
public class RoleEntity {

    @Id
    @GeneratedValue
    private Long roleId;

    private String role;

    @ManyToMany //( mappedBy = "roleEntities") //Bunu kaldırdım
    private Set<UserEntity> userEntities ;


    public RoleEntity(){
        userEntities = new HashSet<>();
    }

正确登录后会出现错误:

ModelMapper映射错误:1)转换器org.modelmapper.internal.converter.CollectionConverter@735060fc无法将java.util.Set转换为java.util.Set。 1个错误

1 个答案:

答案 0 :(得分:0)

我从以下位置更改了RoleEntity类属性:

@ManyToMany //( mappedBy = "roleEntities") 
private Set<UserEntity> userEntities ;

对此:

@ManyToMany (mappedBy = "roleEntities", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<UserEntity> userEntities ;

这就是我解决问题的方式。