延迟加载无法在JPA和Hibernate中工作

时间:2018-11-25 08:24:59

标签: hibernate jpa spring-data-jpa lazy-loading

我在Spring Boot应用程序中将JPA与Hibernate一起使用。每当我尝试使用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;

    }

}

Task.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
}

Service.java

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

Dao.java

public interface ServiceDao extends JpaRepository<Case, Integer>{

}

{
   “ caseId”:1,    “ caseTitle”:“人体工程学”,    “任务”:[
      {
         “ taskId”:1,          “ taskTitle”:“ ca”       },       {
         “ taskId”:2,          “ taskTitle”:“危险”       },       {
         “ taskId”:3,          “ taskTitle”:“补救措施”       }    ] }

任何帮助将不胜感激!

谢谢!

1 个答案:

答案 0 :(得分:0)

要进行调查非常棘手,但是当我使用mapstruct时遇到了这个问题,它恰好是deep/ nested mapping,在此过程中,它调用了惰性加载属性的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();
       }
   }
}

Ref. by kokorin