gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:17:41 26 4
gpt4 key购买 nike

我想使用模型映射器转换具有相同属性的两个对象。然而我不能因为多对多的关系。

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;
}
}

用户实体类:

@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 个错误

最佳答案

我已将 RoleEntity 类属性更改为:

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

对此:

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

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

关于java - 如何使用模型映射器将 2 个类映射到 Dto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51497023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com