首页 > 解决方案 > 让 ModelMapper 忽略 JPA Lazy 且尚未初始化的映射字段

问题描述

如果您使用过 JPA,您可能会遇到经典

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: class, could not initialize proxy - no Session

我正在使用 ModelMapper 将我的休眠对象映射到 DTO,当然,我遇到了这个问题。到目前为止,我最初将所有内容都设置为 EAGER,但我很快了解到这不是解决方案,因为现在所有内容的加载速度都非常慢。所以,现在我回到将事情设置为LAZY.

所以我的问题是:有没有办法自定义它,ModelMapper以便它可以在映射之前检查该字段是否是惰性的 / 如果它是惰性的,不要映射它?

我一直在这里对自定义映射进行一些研究http://modelmapper.org/user-manual/property-mapping/

但我似乎无法找到一种方法来投入一些逻辑。

我在这里找到了解决方案,但这是针对推土机的

编辑:

我正在使用 Spring Boot JPA。这是我的一些代码:

@Data
@Entity
@Table(name = "vm_request")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class VirtualMachineRequest {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // removed other properties

    @OneToMany(mappedBy = "request", cascade = CascadeType.ALL, orphanRemoval = true)
    @ToString.Exclude
    @EqualsAndHashCode.Exclude
    private Set<VirtualMachine> virtualMachines;

}

我将此对象映射到 DTO:

@Data
public class VirtualMachineRequestDTO {

    private Long id;

    // removed other properties

    private Set<VirtualMachineDTO> virtualMachines;

}

像这样使用ModelMapper

public VirtualMachineRequestDTO convertToDTO(VirtualMachineRequest request) {
    VirtualMachineRequestDTO requestDTO = mapper.map(request, VirtualMachineRequestDTO.class);

    return requestDTO;
}

我的问题是,由于该virtualMachines集合是Lazy默认设置的(这适用于某些情况),ModelMapper因此遇到异常LazyInitializationException

ModelMapper如果该字段很懒且尚未初始化,我正在尝试找到一种忽略该字段的方法。

标签: javahibernatejpamodelmapper

解决方案


推荐阅读