实体的Lazy Loading属性正在findAll调用中caming



我开始研究Spring Boot,我对Lazy Loading的使用有一些疑问。

我有@支付实体@PaymentInstitutionEntity@PaymentCustomerEntity

PaymentEntity有一个PaymentInstitution信息,PaymentInstruction有一份PaymentCustomer列表。

我有一个控制器getAllPayments来从数据库中获取所有数据,但我不想在这个获取方法中返回PaymentCustomers列表,所以我在PaymentCustomers属性中添加了FetchType.LAZY,但当我测试这个实现时,PaymentCustomer的列表是caming。如何使paymentCustomer的列表不显示在getAll调用中?

按照我下面的实现:

@Entity(name = "payment")
public class PaymentEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false, length = 20)
private PaymentStatus status;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@Fetch(FetchMode.SELECT)
@JoinColumn(name = "payment_id", nullable = false)
private List<PaymentInstitutionEntity> paymentInstitutions;

// getters and setters implementation here
}

@Entity(name = "payment_institutuion")
public class PaymentInstitutionEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(fetch = FetchType.LAZY)
@Fetch(FetchMode.JOIN)
@JoinColumn(name = "payment_paying_institution_id", nullable = false)
private List<PaymentCustomerEntity> paymentCustomers;

// others columns implementation here
// getters and setters implementation here
}

控制器

@GetMapping("/search-payments")
public ResponseEntity<List<PaymentDto>> getAllPayment() {
final Pagination<PaymentDto> payments = paymentBO.getAll();

return new ResponseEntity<>(payments.map(p -> paymentEntityConverter.convertToDto(p)),
HttpStatus.OK); 
}

BO

@Transactional
public Pagination<PaymentCanonical> getAll() {
List<PaymentEntity> result = paymentEntityRepository.findAll();
return pagination.map(p -> paymentEntityConverter.convertToEntity(p));        
}

注意:如果我把断点放在paymentEntityRepository.findAll((中,结果是用paymentCustomer 列表进行caming

选项1:您可以尝试创建一个新类,该类将作为API的响应发送。您可以在响应中选择所需的字段,然后从PaymentEntity对象中相应地填充这些字段。

选项2:或者,您可以使用JPA Projection只获取所需的列/字段,然后将其作为响应返回。

参考编号:https://www.baeldung.com/spring-data-jpa-projections

现在,以下是使用FetchType.LAZY无法完成任务的原因:简单地说,JPA在内部运行数据库查询。因此,如果您的两个实体之间有关联(关系(,那么如果您使用FetchType.EAGER,它将同时获取所有实体。但是,如果使用FetchType.LAZY,则在需要之前不会提取这些实体。只有当您尝试访问该字段时,它才会被提取。

你可以这样想:

假设您的代码EA和EB中有两个表A和B,以及两个实体类。EA中可以有许多EB。如果使用FetchType.EAGER,那么JPA将立即执行一个查询来获取EA和与其关联的所有EB(执行a和B之间的联接(。但是,如果您使用FetchType.LAZY,则只会提取A的列(没有与B的联接查询(,并且只有当您尝试通过EA的对象访问EB中的任何字段时,才会提取所有关联的B。

参考编号:https://www.baeldung.com/hibernate-lazy-eager-loading

相关内容

最新更新