我正在使用Mapstruct mapper开始我的第一步。我想将JPA数据实体类映射到DTO类。这是我的源类:
@Entity
@Data
@Table(name = "projects")
public class Project {
@Id
private Long Id;
private String projectName;
private String description;
@OneToMany(mappedBy = "project")
List<Sprint> sprints;
@OneToMany(mappedBy = "project")
List<Epic> epics;
@OneToMany(mappedBy = "project")
List<Story> stories;
public Project(Long id, String projectName, String description) {
Id = id;
this.projectName = projectName;
this.description = description;
}
}
这是我的目标类:
@Data
@AllArgsConstructor
public class ProjectDTO {
private Long Id;
private String projectName;
private String description;
}
@Data注释来自Lombok。我想制作一个mapper来将Project映射到ProjectDTO,像Sprint,epics,story这样的属性不应该包含在ProjectDTO中。这是我的mapper界面:
@Mapper
public interface ProjectMapper extends Mapper {
ProjectMapper INSTANCE = Mappers.getMapper(ProjectMapper.class)
ProjectDTO projectToProjectDTO(Project project);
}
当我尝试构建它时,这是我收到的错误消息:
[错误]无法生成没有输入参数的映射方法。
我猜这与ProjectDTO中缺少的属性有关,但不知道要解决它。使用@Mapping,我不能这样做:
@Mapping(source=“sprints”, target= null)
任何帮助,将不胜感激!
同时添加'@NoArgConstructor'。 MapStruct不能(还)通过构造函数处理构造对象。如果你的对象真的是不可变的,那么另一种选择就是使用'@Builder'