我使用带有JPQL分组选择的弹簧数据,一切正常并统计数据,但是当我想访问竞争对象时我得到了这个错误:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
我想要为统计数据收集这些实体
@Entity
public class BetCourse {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "MATCH_ID", nullable = false)
private BetMatch betMatch;
}
@Entity
public class BetMatch {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "betMatch")
private List<BetCourse> courses = new ArrayList<>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "COMPETITION_ID", nullable = false)
private Competition competition;
}
@Entity
public class Competition {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "competition")
private List<BetMatch> betMatches = new ArrayList<>();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "competition")
private List<Stats> stats = new ArrayList<>();
}
我正在将这些类中的数据挖掘到Stats类
@Entity
public class Stats {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "COMPETITION_ID", nullable = false)
private Competition competition;
}
通过此选择:
@Query("select new Stats(" +
"c.course, " +
"c.courseType, " +
"count(*), " +
"SUM(CASE WHEN win = true THEN 1 ELSE 0 END), " +
"c.betMatch.competition) " +
"from BetCourse c " +
group by c.course, c.betMatch.competition, c.courseType")
public List<Stats> computeStatsByBetShop();
当我访问competiton对象时
stat.getCompetition()
我该如何获取此对象?是否有可能以某种方式与联接获取结合?
答案 0 :(得分:3)
在创建了一些代码峰值之后,我找到了一个非常简单易懂的解决方案。不是从BetCourse表开始你的JPQL,而是从那里进行连接,你应该从Competition表开始,然后进行内部连接,直到BetCourse。
这是因为从BetCourse的角度来看,实体是一个ManyToOne,而JPA以某种方式迷失了它们。只是按相反的顺序解决你的问题。
@Query("select new Stats(" +
"c.course, " +
"c.courseType, " +
"count(c), " +
"SUM(CASE WHEN win = true THEN 1 ELSE 0 END), " +
"cpt) " +
"from Competition cpt " +
"inner join cpt.betMatches bm " +
"inner join bm.courses c " +
"group by c.course, c.courseType, cpt")
@ReadOnlyProperty
public List<Stats> computeStatsByBetShop();
这里有一个GitHub minimum code跟随你的课程,所以你可以用它作为例子,以防它仍然不适合你。
干杯,尼古拉斯