Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create many-to-many relationships with Objectify on Google App Engine?

I can't find any documentation on the appropriate way to make a many-to-many relationship between objects using Objectify on Google App Engine.

Can anyone explain how to do this? Do I need to create a new "join" class for this? How efficient will it be?

like image 278
sanity Avatar asked Feb 05 '12 16:02

sanity


2 Answers

What kinds of queries do you need to support?

The simplest solution is:

@Entity
public class StoredObject {
    @Id
    private Long id;

    private List<Long> relatedIds;
}

then, given a StoredObject, you can call objectify.get(StoredObject.class, storedObject.getRelatedIds()) to fetch all the related ids.

To speed up some queries in my own app I did create a few join classes. The expense comes at write-time (you have to maintain the joins) but then read-time is a single index scan with consecutive results!

like image 94
Riley Lark Avatar answered Oct 27 '22 01:10

Riley Lark


This is not the best approach to map many to many relationships in Objectify. The best way is to create an entity that maps the relationship. For example, suppose you have two objects A and B, and they are associated in a certain way. They you could create a class similar to:

Class Link{
    Key<?> master;
    key<?> slave;

    public Link(){

    }

    public setLink(Entity master, Entity slave){
     //initialize

    }

}

Then you may create a Link entity to model a relationship. This automatically maps one to one or many to many relationships

like image 38
Gang Su Avatar answered Oct 27 '22 00:10

Gang Su