如何使用Hibernate检索一组成员对象?
2022-09-02 13:54:57
这个问题是继续我上一个问题。我需要检索复杂类的列表。每个集合中都有几个集合,应该只检索到特定数量的集合。我已经阅读了这些问题1,2的答案,但没有一个解决了我的问题。
我需要查找特定组中位于特定位置的学生列表,以及其地址中的电话号码。我还需要显示每个学生到特定坐标的距离。
下面的代码工作正常,唯一的问题是我无法检索对象列表,例如每个学生的电子邮件列表,组列表和电话列表。
@Entity
public class Student implements java.io.Serializable {
private static final long serialVersionUID = -23949494858373847L;
@Id
@GeneratedValue
String id;
String name;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "student_groups", joinColumns = { @JoinColumn(name = "id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "groupId", nullable = false, updatable = false) })
Set<Group> groups = new HashSet<Group>(0);
..
}
@Entity
public class Address implements java.io.Serializable {
private static final long serialVersionUID = -274634747474623637L;
@Id
@GeneratedValue
String addId;
@Id
@ManyToOne
@JoinColumn(name = "id", nullable = false)
Student student;
@ManyToOne
@JoinColumn(name = "locId", nullable = false)
Location location;
double latitude;
double longitude;
String address;
@OneToMany(mappedBy = "phoneOwner", fetch = FetchType.EAGER)
Set<Phone> phones = new HashSet<Phone>();
String formula = "( 6371 * acos ( cos ( radians("
+ lat
+ ") ) * cos( radians( this_.latitude ) ) * cos( radians( this_.longitude ) - radians("
+ lan + ") ) +" + "sin ( radians(" + lat
+ ") ) * sin( radians( this_.latitude ) ) ) ) as distance";
Session session = sessionFactory.getCurrentSession();
ProjectionList pl = Projections
.projectionList()
.add(Projections.property("std.id").as("id"))
.add(Projections.property("std.name").as("name"))
.add(Projections.property("addr.address").as(
"address"))
.add(Projections.property("location.name").as("location"))
.add(Projections.property("location.city").as("city"))
.add(Projections.property("location.latitude").as("latitude"))
.add(Projections.property("location.longitude").as("longitude"))
.add(Projections.sqlProjection(formula,
new String[] { "distance" },
new Type[] { new DoubleType() }));
List<Students> students = (List<Students) session
.createCriteria(Address.class, "addr")
.createAlias("addr.student", "std")
.createAlias("std.groups", "group")
.createAlias("addr.location", "location")
.setProjection(pl)
.setFetchMode("group", FetchMode.JOIN)
.add(Restrictions.ilike("group.name", groupName))
.add(Restrictions.eq("location.id", locId))
.setResultTransformer(
new AliasToBeanResultTransformer(Students.class))
.list();