如何使用Hibernate Projection检索复杂的类及其成员? [英] How to retrieve a complex class and its members using Hibernate Projection?
问题描述
我有一个类,如下所示,需要使用Hibernate从数据库中检索。
问题是我的课有多个成员,其中大部分都是类,我该如何找回它们?
@实体
public class Student {
@Id
long id;
字符串名称;
字符串fname;
@OneToMany
列表<课程>培训班;
@ManyToOne
经销商;
...
}
@实体
公共类经销商{
@Id
long id;
字符串名称;
@OneToMany(fetch = FetchType.LAZY,mappedBy =cr.dealer,cascade = CascadeType.ALL)
Set< Car> cars = new HashSet< Cars>(0);
..
}
我需要检索学生ID 1和它的所有课程,其经销商和经销商的汽车列表。
我的预测如下,但它不返回任何内容。
...
.setProjection(Projections.projectionList()
.add(Projections.property(friends.cars ).as(cars)
...
从学生s中选择s
离开连接获取s.courses
离开连接获取s.dealer d
离开连接获取d.cars
其中s .id =:id
因为您正在提取两个集合,所以此查询将生成一个笛卡尔积,您需要确保所选的儿童收藏品没有太多入场券。
如果您不想要要运行到笛卡尔产品,您可以简单地运行此查询:
从学生s $ b $中选择s
b left join fetch s.courses
left join fetch s.dealer d
where s.id =:id
然后您访问dealer.cars以使用单独的查询获取该集合:
学生s = ...;
s.getDealer()。getCars()。size();
I have a class as following that need to retrieve from DB using Hibernate. The problem is my class has multiple members and majority of them are classes, how can I retrieve them?
@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);
..
}
I need to retrieve student id 1 and all its courses, its dealer and list of dealers' cars.
My projection is as following but it does not return anything.
...
.setProjection(Projections.projectionList()
.add(Projections.property("friends.cars").as("cars")
...
Because you have a List of Courses and a Set of Cars, you can simply fetch the whole graph in a single query:
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
Because you are fetching two collections, this query will generate a Cartesian Product, so you need to make sure that the selected children collections don't have too many entries.
If you don;t want to run into a Cartesian product, you can simply run this query:
select s
from Student s
left join fetch s.courses
left join fetch s.dealer d
where s.id = :id
and then you access the dealer.cars to fetch that collection with a separate query:
Student s = ...;
s.getDealer().getCars().size();
这篇关于如何使用Hibernate Projection检索复杂的类及其成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!