懒惰加载不适用于带有hibernate的JPA



我在春季启动应用程序中使用带有hibernate的JPA。每当我尝试使用jpa方法获取enities时,它都会返回实体及其内部存在的所有关联。我想按需获取关联的实体(延迟加载(,所以我在域类中提供了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
}

Service.java

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

Dao.java

public interface ServiceDao extends JpaRepository<Case, Integer>{
}


"caseId":1,"案例标题":"人体工程学","tasks":[
{
"taskId":1,"taskTitle":"ca"},{
"taskId":2,"taskTitle":"危险"},{
"taskId":3,"taskTitle":"补救措施"}]}

如有任何帮助,我们将不胜感激!

谢谢!

调查起来很棘手,但我在使用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

相关内容

  • 没有找到相关文章

最新更新