This question is to follow up with my previous question. I need to retrieve a list of complex classes. Each has a few sets in it and just a specific number of them should be retrieved. I've already read answers of these questions 1,2 but none of them solved my issue.
I need to find a list of students that are in a specific group and located in a specific location, and their phone numbers in their address. I also need to show distance of each student to a specific coordinate.
Following code works fine, the only issue is I can not retrieve list of objects for example list of emails, list of groups and list of phones of each student.
@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();