我有以下 DTO 和实体类:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CType {
private Integer id;
// ......
private VType vType;
}
<小时/>
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "c_types")
public class CTypeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private Integer id;
// ......
@Column(name = "v_type_id")
private Integer vTypeId;
}
我需要使用mapstruct映射这些类的对象,这是我的mapstruct:
@Mapper
public interface VCMapper {
@Mappings({
@Mapping(target = "cType", qualifiedByName = "formVType")
})
CType toCType(CTypeEntity cTypeEntity);
List<CType> toCTypes(List<CTypeEntity> cTypeEntities);
@Mappings({
@Mapping(target = "vTypeId", source = "vType.id")
})
CTypeEntity fromCType(CType cType);
List<CTypeEntity> fromCTypeList(List<CType> cTypes);
@Named("formVType")
default VType formVType(CTypeEntity entity, @Context VTypeDao vTypeDao) {
return vTypeDao.findById(entity.getVId());
}
}
问题:当我使用 maven (mvn clean package
) 构建应用程序时,自动执行方法 toCType()
生成的 VCMapperImpl
类不使用合格的 formVType()
默认方法。
问题:
- 为什么 impl 类中没有使用合格的默认方法?
- Mapper 接口(interface)中的默认方法及其用法有什么问题以及如何修复?
最佳答案
之所以不使用合格的formVType
方法是因为@Context
属性。原始方法中没有这样的属性,因此 MapStruct 将与该方法不匹配。如果您将其添加到 toCType
中,那么就会使用它。
为了不拖动 VTypeDao
,我建议您使用 abstract
类并将其注入(inject)其中。
例如
@Mapper
public abstract class VCMapper {
protected VTypeDao vTypeDao;
@Mappings({
@Mapping(target = "cType", qualifiedByName = "formVType")
})
public abstract CType toCType(CTypeEntity cTypeEntity);
public abstract List<CType> toCTypes(List<CTypeEntity> cTypeEntities);
@Mappings({
@Mapping(target = "vTypeId", source = "vType.id")
})
public abstract CTypeEntity fromCType(CType cType);
public abstract List<CTypeEntity> fromCTypeList(List<CType> cTypes);
@Named("formVType")
protected VType formVType(CTypeEntity entity) {
return vTypeDao.findById(entity.getVId());
}
public void setVTypeDao(VTypeDao vTypeDao) {
this.vTypeDao = vTypeDao
}
}
关于java - 在自动生成的实现中不使用按名称限定的映射结构中使用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57325214/