我正在开发一个使用JHipster v2.20.0创建的Web应用程序.使用Eclipse 4.5.0 WTP作为IDE.
Spring配置是基于注释的.
我刚刚将这个拉动与我们的代码合并.
当我尝试在Eclipse中运行应用程序时,我得到以下异常:
[INFO] com.app.tenancy.hibernate.MyCurrentTenantIdentifierResolver - MyCurrentTenantIdentifierResolver.getTenantId(): Couldn't find Company/Tenant for the domain inventario, stopping serving the request
[WARN] org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userManagementResource': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.app.web.rest.mapper.UserManagementMapper com.app.web.rest.UserManagementResource.userManagementMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.app.web.rest.mapper.UserManagementMapper] found for dependency: expected at least 1 bean which qualifies as …Run Code Online (Sandbox Code Playgroud) 我们使用immutables框架来生成所有DTO.现在我们想用mapstruct将这些对象映射到另一个.但是生成的DTO是不可变的,没有setter,也没有构造函数,对应于构建器模式.它们仅通过static builder()-method 访问的相应构建器填充.
我们试图将DTO1映射到DTO2.Builder,如果mapstruct能识别Builder中的setter但这些没有void返回类型但返回Builder本身以进行流畅的连接,那么它将起作用.
所以这是示例的代码.
我们有两个接口
@Value.Immutable
public interface MammalDto {
public Integer getNumberOfLegs();
public Long getNumberOfStomachs();
}
Run Code Online (Sandbox Code Playgroud)
和
@Value.Immutable
public interface MammalEntity {
public Long getNumberOfLegs();
public Long getNumberOfStomachs();
}
Run Code Online (Sandbox Code Playgroud)
然后我们有了maptruct的Mapper接口:
@Mapper(uses = ObjectFactory.class)
public interface SourceTargetMapper {
SourceTargetMapper MAPPER = Mappers.getMapper( SourceTargetMapper.class );
ImmutableMammalEntity.Builder toTarget(MammalDto source);
}
Run Code Online (Sandbox Code Playgroud)
要使用mapstruct来查找Builder,我们需要一个Factory:
public class ObjectFactory {
public ImmutableMammalDto.Builder createMammalDto() {
return ImmutableMammalDto.builder();
}
public ImmutableMammalEntity.Builder createMammalEntity() {
return ImmutableMammalEntity.builder();
}
}
Run Code Online (Sandbox Code Playgroud)
为了生成代码,编译器插件被指示使用两个注释处理器:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration> …Run Code Online (Sandbox Code Playgroud) 我有一个使用gradle的项目,并将mapstruct作为依赖项之一.每当我试图建立项目时,它就失败了.我想这是因为Mapstruct将生成gradle无法找到的impl类.谁能帮助我如何在intellij IDEA中配置它?
谢谢
我目前有一个Map<String, String>包含表单中的值key = value,我想将它们“扩展”为一个真实的对象。
是否可以使用 MapStruct 自动执行此操作,我将如何执行此操作?
澄清一下:我手工编写的代码如下所示:
public MyEntity mapToEntity(final Map<String, String> parameters) {
final MyEntity result = new MyEntity();
result.setNote(parameters.get("note"));
result.setDate(convertStringToDate(parameters.get("date")));
result.setCustomer(mapIdToCustomer(parameters.get("customerId")));
// ...
return result;
}
Run Code Online (Sandbox Code Playgroud) 我使用以下映射器来映射实体:
public interface AssigmentFileMapper {
AssigmentFileDTO assigmentFileToAssigmentFileDTO(AssigmentFile assigmentFile);
AssigmentFile assigmentFileDTOToAssigmentFile(AssigmentFileDTO assigmentFileDTO);
@Mapping(target = "data", ignore = true)
List<AssigmentFileDTO> assigmentFilesToAssigmentFileDTOs(List<AssigmentFile> assigmentFiles);
List<AssigmentFile> assigmentFileDTOsToAssigmentFiles(List<AssigmentFileDTO> assigmentFileDTOs);
}
Run Code Online (Sandbox Code Playgroud)
我只需要忽略映射为集合的实体的"数据"字段.但它看起来@Mapping只适用于单个实体.另外我注意到生成的方法assigmentFilesToAssigmentFileDTOs只是用于assigmentFileToAssigmentFileDTOfor循环.那有什么解决方案吗?
我正在使用MapStruct,mapstruct-jdk8版本1.1.0.Final并定义我通过Spring注入的抽象类.
我正在研究如何通过Junit Test测试它们?我基本上是一个主映射器,它将使用2个子映射器
@Mapper(componentModel = "spring", uses = {SubMapper1.class, SubMapper2.class})
public abstract class MainMapper {
@Mapping(target = "field1", qualifiedByName = {"MyMapper2Name", "toEntity"})
public abstract MyEntity toEntity(MyDto pDto);
public MyDto fromEntity(MyEntity pEntity) {
// Specific code, hence why I use Abstract class instead of interface.
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了几件事,但是无法让mapper正确地进行测试以进行测试.
@RunWith(SpringRunner.class)
public class MainMapperTest {
private MainMapper service = Mappers.getMapper(MainMapper.class);
@Test
public void testToEntity() throws Exception {
.....
Run Code Online (Sandbox Code Playgroud)
java.lang.RuntimeException:java.lang.ClassNotFoundException:找不到com.mappers.MainMapper的实现
我也尝试过@InjectMock,但也没有骰子.
无法实例化名为"service"的@InjectMocks字段.您没有在字段声明中提供实例,因此我尝试构造实例.但是,我失败的原因是:'MainMapper类型是一个抽象类.
并通过Spring @Autowired
引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有'com.mappers.MainMapper'类型的限定bean可用:预期至少有1个bean可以作为autowire候选者.依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}
我猜这可能与注释处理器有关,并且在我启动测试时没有生成映射器.我发现这个类是例子.
但是,在没有最终版本的1.2之前,类AnnotationProcessorTestRunner似乎不可用.
所以我的问题是如何编写Junit测试来测试我在我的代码中通过Spring注入使用的mapstruct抽象类映射器.
我的 Mapper 有问题。我正在使用 mapstruct-processor 来构建 Maven 项目。我一直收到警告:警告:(15, 16)java:未映射的目标属性:“从,到”。警告:(13, 13) java:未映射的目标属性:“clientFrom,clientTo”。我想用它做什么?类 Client 运行良好并创建了一个客户端。
@Entity
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String message;
@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "client_from")
private Client clientFrom;
@ManyToOne
@JoinColumn(name = "client_to")
private Client clientTo;
public Message(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Client getClientFrom() …Run Code Online (Sandbox Code Playgroud) 我从这个来源下载了应用程序https://github.com/springframeworkguru/spring5-mvc-rest/tree/vendor-api 而且我的MapStruct有问题。
@Mapper
public interface CategoryMapper {
CategoryMapper INSTANCE = Mappers.getMapper(CategoryMapper.class);
CategoryDTO categoryToCategoryDTO(Category category);
Run Code Online (Sandbox Code Playgroud)
}
@Data
public class CategoryDTO {
private Long id;
private String name;
}
Run Code Online (Sandbox Code Playgroud)
域类:
@Data
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
Run Code Online (Sandbox Code Playgroud)
服务等级:
@Service
public class CategoryServiceImpl implements CategoryService {
private final CategoryMapper categoryMapper;
private final CategoryRepository categoryRepository;
public CategoryServiceImpl(CategoryMapper categoryMapper, CategoryRepository categoryRepository) {
this.categoryMapper = categoryMapper;
this.categoryRepository = categoryRepository;
}
}
Run Code Online (Sandbox Code Playgroud)
在pom.xml依赖项中,我仅粘贴了两个:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> …Run Code Online (Sandbox Code Playgroud) 我正在创建一个在我的futere项目中使用Mapstruct的poc.
现在我有一个问题如何将自定义方法映射到特殊目标.
例如,我有以下接口映射器:
@Mapper
public interface ItemMapper {
static ItemMapper INSTANCE = Mappers.getMapper(ItemMapper.class);
@Mappings({ @Mapping(source = "number", target = "itemnumber"),
@Mapping(source = "description", target = "description"),
@Mapping(source = "itemClass.name", target = "ic"), @Mapping(source = "optionPart", target = "option"),
@Mapping(source = "plannerCode.code", target = "plannercode"),
@Mapping(source = "plannerCode.name", target = "planner"),
@Mapping(source = "vendor.buyerCode.name", target = "buyer"),
@Mapping(source = "vendor.buyerCode.code", target = "buyerCode"),
@Mapping(source = "vendor.number", target = "vendor"),
@Mapping(source = "vendor.name", target = "vendorName"), @Mapping(source = "pcsItem", target = "pcs"), …Run Code Online (Sandbox Code Playgroud) 最近我们在系统开发过程中遇到了一些冲突。我们发现,我们的团队有 3 种不同的测试方法,我们需要决定哪一种是最好的,并检查是否没有比这更好的方法。
首先,让我们面对一些事实:
- 我们在系统中有 3 个数据层(DTO、域对象、表)
- 我们使用 mapstruct 生成的映射器将每一层的对象映射到另一个层
- 我们使用的是 mockito
- 我们是单元 -测试我们的每一层
现在冲突:让我们假设我们要测试ExampleService哪个ExampleModelMapper用于映射ExampleModel到ExampleModelDto和做哪些测试需要一些额外的业务逻辑。我们可以通过三种不同的方式来验证返回数据的正确性:
a) 我们可以手动将返回对象的每个字段与预期结果进行比较:
assertThat(returnedDto)
.isNotNull()
.hasFieldOrPropertyWithValue("id", expectedEntity.getId())
.hasFieldOrPropertyWithValue("address", expectedEntity.getAddress())
.hasFieldOrPropertyWithValue("orderId", expectedEntity.getOrderId())
.hasFieldOrPropertyWithValue("creationTimestamp", expectedEntity.getCreationTimestamp())
.hasFieldOrPropertyWithValue("price", expectedEntity.getPrice())
.hasFieldOrPropertyWithValue("successCallbackUrl", expectedEntity.getSuccessCallbackUrl())
.hasFieldOrPropertyWithValue("failureCallbackUrl", expectedEntity.getFailureCallbackUrl())
Run Code Online (Sandbox Code Playgroud)
b) 我们可以使用真正的映射器(与正常逻辑相同)来比较两个对象:
assertThat(returnedDto).isEqualToComparingFieldByFieldRecursivly(mapper.mapToDto(expectedEntity)))
Run Code Online (Sandbox Code Playgroud)
c) 最后,我们可以模拟映射器及其响应:
final Entity entity = randomEntity();
final Dto dto = new Dto(entity.getId(), entity.getName(), entity.getOtherField());
when(mapper.mapToDto(entity)).thenReturn(dto);
Run Code Online (Sandbox Code Playgroud)
我们希望使测试尽可能好,同时保持它们的弹性和抗变化性。我们也想保持 DRY 原则。
我们很高兴听到每种方法的任何建议、评论、优缺点。我们也乐于看到任何其他解决方案。
你好。
mapstruct ×10
java ×6
mapping ×3
mapper ×2
spring ×2
unit-testing ×2
builder ×1
gradle ×1
immutability ×1
jhipster ×1
junit ×1
maven ×1
mocking ×1
spring-test ×1