Jac*_*ack 12 java sql orm hibernate hibernate-criteria
我有一个类,需要使用Hibernate从DB检索.问题是我的班级有多个成员,其中大多数是班级,我该如何检索它们?
@Entity
public class Student {
@Id
long id;
String name;
String fname;
@OneToMany
List<Course> courses;
@ManyToOne
Dealer dealer;
...
}
@Entity
public class Dealer {
@Id
long id;
String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "cr.dealer", cascade = CascadeType.ALL)
Set<Car> cars = new HashSet<Cars>(0);
..
}
Run Code Online (Sandbox Code Playgroud)
我需要检索学生ID 1及其所有课程,经销商和经销商汽车列表.
我的预测如下,但它不会返回任何内容.
...
.setProjection(Projections.projectionList()
.add(Projections.property("friends.cars").as("cars")
...
Run Code Online (Sandbox Code Playgroud)
因为您有一个课程列表和一组汽车,所以您可以在单个查询中简单地获取整个图表:
select s
from Student s
left join fetch s.courses
left join fetch s.dealer d
left join fetch d.cars
where s.id = :id
Run Code Online (Sandbox Code Playgroud)
因为您正在获取两个集合,所以此查询将生成笛卡尔积,因此您需要确保所选的子集合没有太多条目。
如果您不想遇到笛卡尔积,您可以简单地运行以下查询:
select s
from Student s
left join fetch s.courses
left join fetch s.dealer d
where s.id = :id
Run Code Online (Sandbox Code Playgroud)
然后您访问 Dealer.cars 以使用单独的查询获取该集合:
Student s = ...;
s.getDealer().getCars().size();
Run Code Online (Sandbox Code Playgroud)