java - 让 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
如果该字段很懒且尚未初始化,我正在尝试找到一种忽略该字段的方法。
解决方案
推荐阅读
- android - Android Studio 模拟器错误和问题
- javascript - Angular:根据不同类别显示
- amazon-web-services - 基于查询字符串的 Cloudfront 重定向行为
- vba - 在状态栏中移动三点分隔符
- css - 有什么方法可以在不清除现有类的情况下将变量中的类名添加到 Angular2 中的宿主元素?
- python-3.x - 在烧瓶中将参数传递给装饰函数时遇到问题
- ios - ARKit - 你可以在会话期间更改 planeDetection 吗?
- javascript - 反应错误 - 无法读取未定义的属性“状态”
- javafx - JavaFX 多个阶段未关闭
- python - arp 使用 scapy 进行 ip 转发