hibernate - 延迟加载在 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" } ] }
任何帮助将不胜感激!
谢谢!
解决方案
调查起来很棘手,但我在使用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();
}
}
}
推荐阅读
- spring-boot - Camel unit testing is failing always, I can't explain myself why the expected is 0 or how to assert the expected correctly
- flutter - Remove transparent hole behind TextSpan?
- python - Python and internet data analysis
- reactjs - 将计数器组件值传递给它的父组件
- gerrit - Gerrit 清单 - 回顾
- javascript - Asp.Net core razor - 如何在 _Layout.cshtml 文件中使用 appsettings.json 值?
- r - 如何更改 plot_model 方面
- mongodb - 使用带有字段值的 mongodb $nin 和 $in 运算符
- python - 如何在kivy中画一个聊天气球?
- javascript - ReactTooltip.show 在功能组件中不起作用