如何使用 mapstruct 将 enum 转换为 POJO 而无需自定义实现?
例如
enum Type {
T1, T2;
private String description;
private Type(String description) {
this.description = description;
}
public String getDescription() { return this.description; }
}
Run Code Online (Sandbox Code Playgroud)
POJO之类的
class TypeDto {
private Type code;
private String description;
}
Run Code Online (Sandbox Code Playgroud)
仅供参考,我使用 MapStruct 1.1.0.Final。
我有 2 个实体CallRecords和CallRecordOperators,它们具有一对多的关系,如下所示
public class CallRecords {
@Id
@Column(name = "id", unique = true)
private String id;
@Column(columnDefinition = "varchar(255) default ''")
private String callerNumber = "";
@OneToMany(mappedBy="callrecord")
private List<CallRecordOperators> callRecordOperators = new ArrayList<CallRecordOperators>();
//getter setters
}
public class CallRecordOperators {
@Id
@Column(name = "id", length = 50, unique = true, nullable = false, insertable = false, updatable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "callRecordId")
private CallRecords callrecord; …Run Code Online (Sandbox Code Playgroud) 对于想要直接返回实体类的 Web 服务开发人员来说,这是一个常见问题。即使加载了我需要的所有数据,仍然有许多我不需要的未初始化的代理和集合。我希望他们只返回 null 而不是抛出延迟加载异常。基本上我只想要 POJO 合约,但是必须清除代理和休眠集合才能获得它(除非休眠中有一些我不知道的新方法)。我可以使用 MapStruct 来执行此操作吗?
如果需要的话,可以了解更多详细信息:
http://www.mojavelinux.com/blog/archives/2006/06/hibernate_get_out_of_my_pojo/
http://www.gwtproject.org/articles/using_gwt_with_hibernate.html
吉利德是我发现的唯一对此有效的药物,但它已不再存在。
我编写了一个使用如下映射的映射结构映射器:
@Mapping(target = "userId", source = "id.userId")
Run Code Online (Sandbox Code Playgroud)
当我查看自动生成的映射结构类时,我偶然发现了该代码:
if ( !foobar.hasId() ) {
return null;
}
Run Code Online (Sandbox Code Playgroud)
这对我来说是一个问题,因为这hasId()不是 mapstruct 所期望的。我可以以某种方式强制 mapstruct 不生成使用此方法但检查id != null或其他内容的代码吗?
我可以使用类似的映射@Mapping(target = "userId", expression= "java(...)"),但我认为应该有另一种方法。
我正在使用 MapStruct 生成的一个映射器:
@Mapper
public interface CustomerMapper {
Customer mapBankCustomerToCustomer(BankCustomerData bankCustomer);
}
Run Code Online (Sandbox Code Playgroud)
默认组件模型是spring(在pom.xml中设置)
<compilerArg>-Amapstruct.defaultComponentModel=spring</compilerArg>
Run Code Online (Sandbox Code Playgroud)
我有一个服务,我在其中注入了客户映射器,并且在运行应用程序时工作正常
@Autowired
private CustomerMapper customerMapper;
Run Code Online (Sandbox Code Playgroud)
但是当我运行涉及@SpringBootTest 的单元测试时
@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class SomeControllerTest {
@Mock
private SomeDependency someDependency;
@InjectMocks
private SomeController someController;
@Test
public void shouldDoSomething() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
我得到一个 org.springframework.beans.factory.UnsatisfiedDependencyException
通过字段“customerMapper”表达的不满意依赖
我想映射嵌套的java对象。Customer.address.houseNumber到userDTO.homeDTO.addressDTO.houseNo。
期望: 当且仅当 Customer.address.houseNumber 不为 null 时,才homeDTO在 下创建对象userDTO。否则,不要创建任何目标对象。
问题: 我已经"NullValueCheckStrategy.ALWAYS"在映射器中使用了,但是mapstruct正在检查是否address不为空,然后它会创建homeDTO. 里面address,houseNumber就是null。我想要空检查直到houseNumber(叶/最后一级对象),然后创建目标对象。
我怎样才能实现这个目标?
这是我正在使用的映射。
@Mapper( nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS )
public interface Customer2UserMapper {
@Mapping(source="address.houseNumber", target="homeDTO.addressDTO.houseNo" )
void mapCustomerHouse(Customer customer, @MappingTarget UserDTO userDTO) ;
}
Run Code Online (Sandbox Code Playgroud)
我有 2 个对象 ExpertJpa 到 ExpertDto 的现有映射,需要另一个参数来过滤 ExpertJpa。该地图工作正常,现在我尝试将 ExpertJpa 列表转换为 ExpertDto 列表,我添加第二个参数。
@Mappings({
@Mapping(target = "status", ignore = true),
@Mapping(target = "profile", source = "input.expertProfile"),
@Mapping(target = "engagementId", expression = "java(new MapperHelper().ReturnExpertEngagementIdByApiKey(input,identity))"),
@Mapping(target = "campaignId", expression = "java(new MapperHelper().ReturnExpertCampaignIdByApiKey(input,identity))"),
})
Expert ExpertJpaToExpert(com.consumer.expert.dbaccessor.entities.Expert input, Identity identity);
List<Expert> ListExpertsJpaToListExperts(List<com.consumer.expert.dbaccessor.entities.Expert> input, Identity identity);
Run Code Online (Sandbox Code Playgroud)
在构建时,我收到错误消息,指出 List 是一个接口,不能是实例......
错误:(53, 18) java:返回类型 java.util.List 是抽象类或接口。提供非抽象/非接口结果类型或工厂方法。
我正在尝试将 mapstruct 与 Gradle 一起使用,但取得的成功有限。当我在应用程序中使用它时,一切似乎都工作正常,但是当我尝试编写一些测试时,Spring 无法正确自动装配 MapStruct (它只返回 NullPointer 异常)。我正在使用 Gradle 5.4.1、Junit5 和 IntelliJ 2019.1.2。
这是构建文件夹,没有为测试类生成映射器。

包含代码的存储库位于: https://github.com/MirkoManojlovic/mapstruct-example
@Mapper(unmappedTargetPolicy = ReportingPolicy.WARN,
componentModel = "spring",
injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface ItemMapper {
ItemDto toDto(Item item);
Item toItem(ItemDto itemDto);
}
Run Code Online (Sandbox Code Playgroud)
public class ItemRepository {
public ItemDto getItemDto() {
return new ItemDto("item 1");
}
public Item getItem() {
return new Item(1, "item 1", 20);
}
}
Run Code Online (Sandbox Code Playgroud)
@Service
@RequiredArgsConstructor
@Log4j2
public class ItemService {
private final ItemRepository itemRepository;
private final ItemMapper …Run Code Online (Sandbox Code Playgroud) 我对 mapstruct 中的 @ManyToOne 映射有疑问。我有两张桌子
第一个:
@Entity
@Table(name = "members", schema = vsm)
public class MemberEntity{
@Column(name = "id", nullable = false)
protected Long id;
@ManyToOne(optional = false)
@JoinColumn(name = "case_id", nullable = false)
private CaseEntity case;
}
Run Code Online (Sandbox Code Playgroud)
第二个:
@Entity
@Table(name = "cases", schema = vsm)
public class CaseEntity {
@Column(name = "id", nullable = false)
protected Long id;
@Column(name = "description", nullable = false)
protected String description;
}
Run Code Online (Sandbox Code Playgroud)
我有一个像这样的案例:
public class CasesDto{
protected Long id;
protected String description;
private …Run Code Online (Sandbox Code Playgroud) I have the following example in which i have a separate domain layer and a separate persistence layer. I am using Mapstruct for mapping and I get StackOverflow when mapping from domain to entity or from entity to domain because of the bidirectional reference that always gets called on -> infinite loop scenario. How can I use Mapstruct for this scenario?
class User {
private UserProfile userProfile;
}
class UserProfile {
private User user;
}
@Entity
class UserEntity {
@OneToOne …Run Code Online (Sandbox Code Playgroud) mapstruct ×10
java ×7
hibernate ×3
dto ×2
entity ×1
enums ×1
mapping ×1
nested ×1
null ×1
one-to-many ×1
spring ×1
spring-boot ×1
unit-testing ×1