How to define one to many relation in Siena and GAE?

529 views Asked by At

Suppose I have two domain models Author and Book. So Author can have one or many books.

From the documentation for Siena, it seems to suggest something like:

public class Author extends Model {

    @Id
    public Long id;

        public String name;


    public Book book;
}

But I was expecting something like:

public class Author extends Model {

    @Id
    public Long id;

    public String name;

    public List<Books> books = new ArrayList<Book>();
}

So in my code I can do something like:

Book book1 = new Book(), boo2 = new Book();

Author author = new Author(); author.books.add(book1); author.books.add(book2); author.insert();

But this does not seem right from the documentation Siena

The question is what is the correct solution?

1

There are 1 answers

0
mandubian On

Remember that Siena is based on NoSQL concepts so no join as in SQL. Anyway, you can design a one2many relation naturally.

In traditional Siena, you would have written it like that using an auto-query:

class Author {
...
 @Filter("author")
 public Query<Book> books; // this is called an "automatic-query"
...
}

class Book {
...
    Author author;
...
}

Then you would get its books like that :

List<Book> booksBlabla = author.books.filter("your_field", "blabla").fetch();

As you use GAE, there is a new intuitive syntax using Many documented there: https://github.com/mandubian/siena/blob/master/source/documentation/manuals/relation_syntax_many.textile

class Author {
...
   public Many<Book> books; // this is called an "automatic-query"
...
}

and then, you can access the book as a list or as a query:

List<Book> theBooks = books.asList();
List<Book> theFilteredBooks = books.asQuery().filter("...", "...").fetch();

And there is a big advantage in this syntax when you create author with book

Author author = new Author("name");
author.books.add(new Book("title1"), new Book("title2"), new Book("title3"));
author.insert();

it inserts author and the books associated to the author (but if you delete the author, it won't delete the books as siena doesn't manage such cascade and lets you do it).

You can read the doc here before and ask questions on the siena google group, we'll help you if we can.