【发布时间】:2020-07-14 01:46:01
【问题描述】:
我已经搜索过这个问题,并且在过去的几天里一直被卡住,所以我希望你能帮忙。我将尝试用一个基本概念来总结我遇到的问题,因为这样我就可以将其应用于我更复杂的问题。
我有 2 个实体对象:学生和课程。请注意,学生实体创建了一个包含 3 列的表,并且还有一个额外的“金额”属性。这里的想法是我不想存储我在执行查询时将执行的聚合。所以学生购买了几门课程,每门课程都有成本。我想总结总成本,使其在 json 中处于同一级别(请参阅期望的结果)。
我卡住的地方是我的选择查询。当我删除 a.course 时一切正常。我的 json 显示了聚合,一切都很好。但显然,当然缺少清单。所以我的总体问题是,当我的查询中嵌入了嵌套列表对象时,我的选择查询应该是什么样子?
select new Student(a.id, a.name, a.course,
期望的结果:
{
"id": 1,
"name": "Billy"
"course":
{[
"id" : 1,
"courseName" : "Math",
"cost" : 12.99
],[
"id" : 2,
"courseName" : "Science",
"cost" : 15.99
]
}
"amount" : 28.98
}
public class Student {
@Id
@GeneratedValue(
strategy= GenerationType.AUTO,
generator="PRIVATE_SEQ"
)
@GenericGenerator(
name = "native",
strategy = "native"
)
private long id;
@Column(name = "name", nullable = false, length = 25)
private String name;
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="student_id")
private List<Course> course;
private BigDecimal amount;
public Student(Long id, String name, List<Course> course, BigDecimal amount) {
this.id = id;
this.name = name;
this.course = course;
this.amount = amount;
}
}
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(
strategy= GenerationType.AUTO,
generator="PRIVATE_SEQ"
)
@GenericGenerator(
name = "native",
strategy = "native"
)
private long id;
@Column(name = "coursename", nullable = false, length = 30)
private String courseName;
@ManyToOne
@JoinColumn(name="student_id")
private Student student;
@Column(name = "cost", nullable = false)
private BigDecimal cost;
public Course(Long id, String courseName, BigDecimal cost) {
this.id = id;
this.courseName = courseName;
this.cost = cost;
}
List<Student> students = session
.createQuery(" select new Student(a.id, a.name, a.course, SUM(CASE WHEN b.cost <> 0 THEN b.cost ELSE 0 END)) from Student a "
+ "Left join fetch Course b on b.id = d.budget "
+ "group by b.id ")
.getResultList();
【问题讨论】: