Issue
I have a Post Entity and a Post DTO, currently trying to map the DTO to Entity but it's giving me a Qualifier error. No method found annotated with @Named#value: [ getUserByUsername ].
Any help would be greatly appreciated, these are my current files:
PostDTO:
@Getter
@Setter
public class PostDTO {
private String author;
@Size(max = 755)
private String content;
}
Post Entity:
@Entity
@Table(name = "POST")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@ManyToOne(fetch = FetchType.EAGER, cascade= CascadeType.ALL)
@JoinColumn(name = "POSTS")
private User author;
@Column(name = "POSTED_AT", nullable = false)
private LocalDateTime dateTime;
@Size(max = 755)
@Column(name = "CONTENT", nullable = false, length = 755)
private String content;
}
PostMapper:
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE, uses = {MappingUtil.class, PostRepository.class})
public interface PostMapper {
// since the author attribute on postDTO is a String, we use mapstruct to find
// within our database the matching user to that username and return the user object
@Mapping(source = "author", target = "author", qualifiedByName = {"getUserByUsername"})
Post toEntity(PostDTO postDTO);
PostDTO toDTO(Post post);
}
MappingUtils:
@Component
public class MappingUtil {
private final UserRepository userRepository;
MappingUtil(UserRepository userRepository) {
this.userRepository = userRepository;
}
@BeanMapping(qualifiedByName = "getUserByUsername")
public User getUserByUsername(String username){
return userRepository.findByUsername(username);
}
}
So whenever I run the build, the mapper can't find the @Named
annotation with the getUserByUsername method on the MappingUtil class, I've tried a few approaches but can't seem to fix it
Solution
The annotaion @BeanMapping doesn't help you. Use @Name instead and the error will be disappeared.
@Named("getUserByUsername")
public User getUserByUsername(String username) {
return userRepository.findByUsername(username);
}
Also you need a mapping for converting User to UserName in toDTO(Post post) like this:
@Mapping(source = "author.userName", target = "author")
PostDTO toDTO(Post post);
Answered By - Azadi Yazdani
Answer Checked By - Timothy Miller (JavaFixing Admin)