Jhipster中的默认值不是使用DTO,而是直接使用。所以我的第一个实体company
不使用 DTO。现在,我已经生成了一个实体tour
,该实体与公司具有多对一关系,并具有服务层和DTO支持。
在生成过程中,我收到以下消息:
WARNING! This entity has the DTO option,
and it has a relationship with entity "company" that doesn't have the DTO option.
This will result in an error.
当我编译生成的项目时,我收到一个错误,如承诺的那样:
java:11: error: cannot find symbol
@Mapper(componentModel = "spring", uses = {UserMapper.class, CompanyMapper.class})
我试图在注释中删除公司映射器.class然后得到以下行的错误:
@Mapping(source = "companyId", target = "company")
Tour toEntity(TourDTO tourDTO);
Ambiguous mapping methods found for mapping property "java.lang.Long companyId" to java.lang.Object: de....Tour fromId(java.lang.Long id), de...User de.....mapper.UserMapper.userFromId(java.lang.Long id).
我是否需要建立一个公司DTO,或者有没有其他方法可以告诉mapstruct访问公司?
我想我已经用以下内容修复了映射器:
首先,我从@Mapper
注释中删除了"CompanyMapper.class",就像我在问题中描述的那样。
我向映射器添加了一个方法,以从 id 创建公司。如果我理解正确,这使映射器能够在创建 Tour 对象时调用"tour.setCompany()
",并且TourDTO
中有一个companyId
。
default Company companyFromId(Long id) {
if (id == null) {
return null;
}
Company obj = new Company();
obj.setId(id);
return obj;
}
最初提出的答案是解决问题的一种方法。
另一种方法,不确定是否需要和需要,是直接从数据库中获取Company
(然后获得托管实体(。
如果您有带有方法findById(Long)
的CompanyRepository
,那么您可以这样做。
@Mapper(componentModel = "spring", uses = {UserMapper.class,
CompanyRepository.class})
public interface MyMapper {
@Mapping(source = "companyId", target = "company")
Tour toEntity(TourDTO tourDTO);
}
这在调用其他映射器中有更详细的解释