首页 > 解决方案 > 延迟加载在 JPA 中无法使用休眠

问题描述

我在我的 Spring Boot 应用程序中使用 JPA 和休眠。每当我尝试使用 jpa 方法获取实体时,它都会返回实体以及其中存在的所有关联。我想按需获取关联的实体(延迟加载),所以我在我的域类中提供了 fetch=FetchType.LAZY 。但它仍然返回所有条目。

下面是代码: Case.java

    @Entity
    @Table(name="smss_case")
    public class Case implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -2608745044895898119L;

    @Id
    @Column(name = "case_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer caseId;

    @Column( name="case_title" )
    private String caseTitle;

    @JsonManagedReference
    @OneToMany(mappedBy="smmsCase", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
    private Set<Task> tasks;

    }

}

任务.java

@Entity
@Table(name="task_prop")
public class Task implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -483515808714392369L;

    @Id
    @Column(name = "task_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer taskId;

    @Column(name="task_title")
    private String taskTitle;

    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn( name="case_id", nullable=false)
    private Case smmsCase;
// getters and setters
}

服务.java

public Case getCases(Integer id) {
        return dao.findById(1).get();
}

道.java

public interface ServiceDao extends JpaRepository<Case, Integer>{

}

{
"caseId":1, "caseTitle":"ergonomics", "tasks":[
{
"taskId":1, "taskTitle":"ca" }, {
"taskId":2, "taskTitle":"hazards" }, {
"taskId":3, "taskTitle":"remedy" } ] }

任何帮助将不胜感激!

谢谢!

标签: hibernatejpaspring-data-jpalazy-loadingmapstruct

解决方案


调查起来很棘手,但我在使用mapstruct时遇到了这个问题,它碰巧进行了深度/嵌套映射,并且在此过程中,它调用了延迟加载属性的 getter。当我使用 mapstrct 时,这个问题得到了解决@BeforeMapping

@Mapper
public interface HibernateAwareMapper {
    @BeforeMapping
    default <T> Set<T> fixLazyLoadingSet(Collection<?> c, @TargetType Class<?> targetType) {
        if (!Util.wasInitialized(c)) {
            return Collections.emptySet();
        }
        return null;
    }

    @BeforeMapping
    default <T> List<T> fixLazyLoadingList(Collection<?> c, @TargetType Class<?> targetType) {
        if (!Util.wasInitialized(c)) {
            return Collections.emptyList();
        }
        return null;
    }

   class Util {
       static boolean wasInitialized(Object c) {
           if (!(c instanceof PersistentCollection)) {
               return true;
           }

           PersistentCollection pc = (PersistentCollection) c;
           return pc.wasInitialized();
       }
   }
}

参考。通过 kokorin


推荐阅读