根据Mapstruct文档,可以通过定义被引用对象(对象B(的映射方法,将包含另一个对象(对象A(的对象(对象C(映射到DTO。但若我只需要映射那个对象(对象B(的属性,而不需要映射整个对象呢?
描述问题-我正在研究Spring Boot,这是我的项目-https://github.com/Alex1182-St/java-spring-jpa-postgresql
出于安全目的,我需要将我的AppUserEntity映射到AppUserDetailsDTO(实现UserDetails(,尤其是我需要将名称从我的AppUserEntity的属性private Set<RoleEntity> roles
映射到我的
AppUserDetailsDTO的private Collection<GrantedAuthority> authorities
使用Kotlin很容易(authority=roles.map{it.name}(:
fun AppUserEntity.toAppUserDetailsDTO() = AppUserDetailsDTO(
id = id,
username = appUserLogin,
password = appUserPassword,
authorities = roles.map { it.name },
isEnabled = isEnabled,
isAccountNonLocked = isAccountNonLocked,
isAccountNonExpired = isAccountNonExpired,
isCredentialsNonExpired = isCredentialsNonExpired
)
但是如何使用Java和Mapstruct呢?
在Mapstruct上,可以使用注释上的表达式属性expression = "java( yourJavaCodeHere )"
对注释进行映射。
您的映射器看起来像:
@Mapper(componentModel = "spring")
public abstract class AppUserDetailsDtoMapper {
@Mappings({
@Mapping(target = "username", source = "appUserLogin"),
@Mapping(target = "password", source = "appUserPassword"),
@Mapping(target = "authorities", expression = "java( mapAuthorities(user.getRoles()) )")
})
public abstract AppUserDetailsDTO toAppUserDetailsDTO(AppUserEntity user);
protected Collection<GrantedAuthority> mapAuthorities(Set<RoleEntity> roles) {
// Map the authorities here
}
}