【发布时间】:2019-12-04 19:59:55
【问题描述】:
我有以下 DTO 类:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Conclusion {
private Integer id;
// ......
private List<CType> cTypes;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CType {
private Integer id;
// ......
private VType vType;
}
还有它们对应的实体类:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "conclusion")
public class Conclusion {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private Integer id;
// ......
@OneToMany
@JoinColumn(name = "id")
private List<CTypeEntity> cTypeEntities;
}
@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;
}
此外,所有相应的 Dao 和 JPA Repository 接口都存在。 现在,我正在编写我的 mapstruct Mapper 接口,它应该用于将实体映射到 DTO,反之亦然。这是映射器:
@Mapper
public interface ConclusionMapper {
@Mappings({
@Mapping(target = "cTypes", source = "cTypeEntities")
})
Conclusion toConclusion(ConclusionEntity entity);
List<Conclusion> toConclusionList(List<ConclusionEntity> entities);
@Mappings({
@Mapping(target = "cTypeEntities", source = "cTypes")
})
ConclusionEntity fromConclusion(Conclusion conclusion);
List<ConclusionEntity> fromConclusionList(List<Conclusion> conclusions);
@Mappings({
@Mapping(target = "cType", source = "vTypeId", qualifiedByName = "formVType")
})
ConclusionTaxType toCType(CTypeEntity cTypeEntity);
List<CType> toCTypes(List<CTypeEntity> cTypeEntities);
CTypeEntity fromCType(CType cType);
List<CTypeEntity> fromCTypeList(List<CType> cTypes);
@Named("formVType")
default VType formVType(CTypeEntity entity) {
// TODO: instantiate a DAO which will return an instance of VType
VTypeDao dao; // instantiate somehow
return vTypeDao.findById(entity.getVId());
}
}
VTypeDao 看起来像这样:
public interface VTypeDao {
VType findById(int id);
boolean exists(int id);
List<VType> findAll();
}
@Component
public class VTypeDaoImpl implements VTypeDao {
private final VTypeRepo vTypeRepo;
public VTypeDaoImpl(VTypeRepo vTypeRepo) {
this.vTypeRepo = vTypeRepo;
}
// ............................. method implementations
}
我的问题是:如何实例化 VTypeDao 的对象(或者至少是 VTypeRepo,以便我可以将 if 作为参数传递给 VTypeDaoImpl)?
没有工厂类用于获取 VTypeDao 的适当实现。
编辑: VTypeDao 及其实现是我项目的第三方组件。
【问题讨论】:
-
VTypeDao 和 MapStruct 有什么关系?顺便说一句:您可以向名为 componentmodel 的 @Mapper 注释添加一个参数。您可以将其设置为 spring,这使映射器成为 spring 组件。
-
VTypeDao 和 MapStruct 之间没有关系。 VTypeDao 是一种第三方 DAO,我需要在我的 MapStruct 中使用它。据我了解,用 componentmodel 注释我的 MapStruct 只允许我在某些 DAO 实现中使用它。我的目标是相反的:我希望在我的 MapStruct 中使用 VTypeDao。
标签: java spring spring-boot spring-data-jpa mapstruct