Created
August 16, 2013 19:43
-
-
Save vsigler/6252929 to your computer and use it in GitHub Desktop.
Demonstration of valid and invalid uses of one-to-many relationship in ActiveAndroid.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.activeandroid.test; | |
import com.activeandroid.Model; | |
import com.activeandroid.annotation.Column; | |
import com.activeandroid.annotation.Table; | |
import java.util.List; | |
import static junit.framework.Assert.assertEquals; | |
/** | |
* Tests model relationships. | |
*/ | |
public class ModelRelationshipTest extends ActiveAndroidTestCase { | |
/** | |
* Correct use of the one-to-many relatinship support in AA. | |
*/ | |
public void testOneToMany() { | |
One one = new One(); | |
one.save(); | |
Many many1 = new Many(); | |
Many many2 = new Many(); | |
many1.setOne(one); | |
many2.setOne(one); | |
many1.save(); | |
many2.save(); | |
List<Many> manyList = one.many(); | |
assertEquals(2, manyList.size()); | |
} | |
/** | |
* Invalid use - collection change does not reflect back! | |
*/ | |
public void testOneToManyInvalidUseCollection() { | |
One one = new One(); | |
one.save(); | |
Many many = new Many(); | |
many.save(); | |
// this will not work the way you expect!! | |
// result of many() is a list returned from a query, | |
// changes to it are not reflected back to the database! | |
one.many().add(many); | |
one.save(); | |
List<Many> manyList = one.many(); | |
//now you could expect the Many instance to be in the collection, but in fact, it's empty | |
//as the collection is just a one-way trip. | |
assertEquals(1, manyList.size()); | |
} | |
/** | |
* Invalid use - querying for related models on an unsaved model does not | |
* make sense. | |
*/ | |
public void testOneToManyInvalidUnsaved() { | |
One one = new One(); | |
//one.save(); //if you uncomment this, the test will pass | |
Many many1 = new Many(); | |
Many many2 = new Many(); | |
many1.setOne(one); | |
many2.setOne(one); | |
many1.save(); | |
many2.save(); | |
one.many(); //there will be a NPE here, because one.getId() returns null | |
} | |
@Table(name = "One") | |
public static class One extends Model { | |
public List<Many> many() { | |
return getMany(Many.class, "OneFK"); | |
} | |
} | |
@Table(name = "Many") | |
public static class Many extends Model { | |
@Column(name = "OneFK") | |
private One one; | |
public One getOne() { | |
return one; | |
} | |
public void setOne(One one) { | |
this.one = one; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment