Thursday, 19 September 2013

Play 2/Ebean ManyToMany JSON Results

Play 2/Ebean ManyToMany JSON Results

I'm using Play! 2.1.4 framework with Ebean/MySQL.
The system basically keeps track of courses, and their requirements. Eg,
if you want to take Advanced Art, you must first take regular Art. This is
a ManyToMany Relationship, as I understand, but I could be wrong.
Here's my model: @Entity public class Course {
public static Model.Finder<Long,Course> find = new
Model.Finder<Long,Course>(Long.class, Course.class);
@Id
private Long id;
private String name;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable( name = "course_course",
joinColumns = @JoinColumn(name = "course_id1"),
inverseJoinColumns = @JoinColumn(name = "course_id2"))
private Set<Course> courseRequirements = new HashSet<Course>();
private String availability;
private Long category;
@Lob
private String description;
@Lob
private String otherRequirements;
private Long bucketId;
// Getters and setters...
Here's how I return the JSON to my frontend:
List<Course> courses =
Ebean.find(Course.class).fetch("courseRequirements").findList();
JsonContext jsonContext = Ebean.createJsonContext();
return ok(jsonContext.toJsonString(courses));
However, in the "courseRequirements" key in the JSON, it opens up a new
array with full course objects in it. I just want to get an array of the
course IDs it requires, for example: courseRequirements: [3, 5] means
that: this course requires you to take courses with ID 3 and 5 first.
I rewrote my getter to this: public Set getCourseRequirements() { Set
requiredCourseIds = new HashSet();
for(Course course : courseRequirements)
{
requiredCourseIds.add(course.getId());
}
return requiredCourseIds;
}
because I thought that Ebean will pull that when trying to fill in the
JSON key, but that's not the case.
How can I change it so that it only returns an array of course IDs for the
courseRequirements key, instead of full objects?
Thanks!

No comments:

Post a Comment