Search code examples
playorm

ManytoMany in playorm


As playorm supports ManytoMany, I have two questions related to this:

  1. How does the entities stored in database in case of ManyToMany. i.e., how many tables/column families are required.
  2. Also, in the examples given in com.alvazan.test.db package, this is being used in Account.java:

    @NoSqlManyToMany
    private CursorToMany<Activity> activitiesCursor = new CursorToManyImpl<Activity>();
    

    A similar example is given here . My concern here is that do we always need to use CursorToMany for implementing ManyToMany?

    If yes, will it not not cause any issue since CursorToMany does not belong to data layer(Entities will not remain POJO).

    If no, then what is the other way round?


Solution

  • The link you link to shows you the pojo way of many to many but with the pojo method you could get OutOfMemoryExceptions if you have tooooo many in your list which is why we also provide you with the cursor. Let's change the link example you gave me to the following....

    public class Student {
      @NoSqlId
      private String id;
      private String firstName;
      private String lastName;
      @ManyToMany
      private List<Course> courses = new ArrayList(); //constructing avoids nullpointers
    }
    
    public class Course {
      @NoSqlId
      private String id;
      private String name;
      private String description
      @ManyToOne
      private Lecturer lecturer;
      @ManyToMany
      private List<Student> students = new List<Student>();
    }
    

    For any *ToMany(OneToMany, ManyToMany) we store a LIST of foreign keys in the row itself. In the example above, there is ONLY two tables. A row is going to look like this

    studentrowkey -> firstName="dean", lastName="hiller", courses:courseFk56=null, courses:courseFk78=null, courses:courseFk98=null, etc. etc.
    

    Notice we did not have it this way

    studentrowkey -> firstName="dean", lastName="hiller", courses=courseFk56,courseFk78, courseFk98
    

    The reason we use the former is column operations are independent so if two servers read in the same student...one server may add courseFk200 and another may delete courseFk56 from the student and you both actions will take affect. If you follow the latter method instead one of the server's changes would be lost.

    later, Dean