JPA延迟加载在Spring Boot中不起作用 [英] JPA Lazy loading is not working in Spring boot

查看:288
本文介绍了JPA延迟加载在Spring Boot中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google上搜索了很多东西,而Spring Boot(最新版本)可能没有延迟加载的确很奇怪.以下是我的代码片段:

I googled a lot and It is really bizarre that Spring Boot (latest version) may not have the lazy loading is not working. Below are pieces of my code:

我的资源:

 public ResponseEntity<Page<AirWaybill>> searchAirWaybill(CriteraDto criteriaDto, @PageableDefault(size = 10) Pageable pageable{
airWaybillService.searchAirWaybill(criteriaDto, pageable);
        return ResponseEntity.ok().body(result);
}

我的服务

@Service
@Transactional
public class AirWaybillService {

//Methods

 public Page<AirWaybill> searchAirWaybill(AirWaybillCriteriaDto searchCriteria, Pageable pageable){
    //Construct the specification
            return airWaybillRepository.findAll(spec, pageable);
   }
}

我的实体:

@Entity
@Table(name = "TRACKING_AIR_WAYBILL")
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@airWaybillId") //to fix Infinite recursion with LoadedAirWaybill class
public class AirWaybill{
//Some attributes
    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "FK_TRACKING_CORPORATE_BRANCH_ID")
    private CorporateBranch corporateBranch;
}

在调试时,我仍然将所有延迟加载的属性都加载了.参见下图.

And when debugging, I still getting all lazy loaded attributed loaded. See image below.

我的问题之一是杰克逊会参与这种行为吗? 我可能错过了激活延迟加载的任何方式吗?

One of my questions is could Jackson be involved in such behaviour? Is there any way that I may have missed to activate the lazy loading?

编辑

另一个问题,调试器可以参与破坏延迟加载吗?

Another question, could the debugger be involved in ruining the lazy loading?

对于规格版本,我有:

public static Specification<AirWaybill> isBranchAirWayBill(long id){
    return new Specification<AirWaybill>() {
        @Override
        public Predicate toPredicate(Root<AirWaybill> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            return cb.equal(root.join("corporateBranch",JoinType.LEFT).get("id"),id);
        }
    };
}

推荐答案

使用@Transactional的方法中存在休眠会话. 在Service类之外传递实体是一种不好的做法,因为在离开search方法后,会话将关闭.另一方面,您的实体包含惰性的初始化集合,一旦会话关闭,就无法提取它们.

Hibernate Session exists within method with @Transactional. Passing entity outside Service class is a bad practise because session is being closed after leaving your search method. On the other hand your entity contains lazy initialised collections, which cannot be pulled once session is closed.

好的做法是将实体映射到传输对象上,然后从服务(不是原始实体)中返回那些传输对象.

The good practise is to map entity onto transport object and return those transport objects from service (not raw entities).

这篇关于JPA延迟加载在Spring Boot中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆