Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many to many relationship in java google ap engine

how would i go about creating a many-many relationship among data objects in google app engine (using jdo)

The app engine page talks about 1-many and 1-1 but not many-many. Any code example will be highly appreciated

like image 391
Midhat Avatar asked Dec 22 '22 09:12

Midhat


1 Answers

Typically for a many-many, you would do a two 1-manys. And from the app engine docs on relationships:

Many-to-Many Relationships We can model a many-to-many relationship by maintaining collections of keys on both sides of the relationship. Let's adjust our example to let Food keep track of the people that consider it a favorite:

Person.java
import java.util.Set;
import com.google.appengine.api.datastore.Key;

// ...
    @Persistent
    private Set<Key> favoriteFoods;
Food.java
import java.util.Set;
import com.google.appengine.api.datastore.Key;

// ...
    @Persistent
    private Set<Key> foodFans;

In this example the Person maintains a Set of Key values that uniquely identify the Food objects that are favorites, and the Food maintains a Set of Key values that uniquely identify the Person objects that consider it a favorite. When modeling a many-to-many using Key values, be aware that it is the app's responsibility to maintain both sides of the relationship: Album.java

// ...
public void addFavoriteFood(Food food) {
    favoriteFoods.add(food.getKey());
    food.getFoodFans().add(getKey());
}

public void removeFavoriteFood(Food food) {
    favoriteFoods.remove(food.getKey());
    food.getFoodFans().remove(getKey());
}

Note that unless an instance of Person and an instance of Food contained in Person.favoriteFoods are in the same entity group, it is not possible to update the person and that favorite food in a single transaction. If it is not feasible to colocate the objects in the same entity group, the application must account for the possibility that a person's favorite foods will get updated without the corresponding update to the food's set of fans or, conversely, that a food's set of fans will get updated without the corresponding update to the fan's set of favorite foods.

like image 89
Corey D Avatar answered Jan 29 '23 15:01

Corey D