GreenDAO: store list of entities in other entity

心已入冬 提交于 2019-12-03 08:26:31

I think you don't have to know SQL, but you'll have to know basic Database knowledge and be clear to your E-R Model, which I think you already have.

If you use greenDAO and implement the relationship between Book and BookShelf, you don't need to keep the list of books in your BookShelf enity.

In your DaoGenerator.java , you simply declare the schema

    Entity bookShelf = schema.addEntity("BookShelf");
    bookShelf.addIdProperty();

    Entity book = schema.addEntity("Book");
    book.addIdProperty();
    book.addStringProperty("name");
    Property bookFKShelves = book.addLongProperty("bookShelf_id").notNull().getProperty();

    book.addToOne(bookShelf, bookFKShelves);
    bookShelf.addToMany(book, bookFKShelves);

Once your generate the code. Use them in your Android code:

        DevOpenHelper helper = new DaoMaster.DevOpenHelper(this.getActivity(),
                "BookStore", null);
        db = helper.getWritableDatabase();
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
        BookDao mBookDao = mDaoSession.getBookDao();
        BookShelfDao mBookShelfDao = mDaoSession.getBookShelfDao();

        // Insert
        BookShelf bs = new BookShelf();
        Book b1 = new Book();   b1.setName("B1");   b1.setBookShelf(bs);
        Book b2 = new Book();   b2.setName("B2");   b2.setBookShelf(bs);
        Book b3 = new Book();   b3.setName("B3");   b3.setBookShelf(bs);

        mBookDao.insert(b1);
        mBookDao.insert(b2);
        mBookDao.insert(b3);
        mBookShelfDao.insert(bs);

        // Select
        for(BookShelf bss :mBookShelfDao.loadAll()){
            for (Book b :bss.getBookList())
                Lod.d(TAG,"Book Name: "+b.getName());
        }

Basically you don't need to know sql for greendao:

You just define your entities (object-classes) and relations between them.

To your question:

There are two possibilities:

  • Bookshelve can contain many books and one book can only be in one bookshelve: Your approach is correct.
  • bookshelve can contain many books and one book can be in many bookshelves: You should define an emtity bookshelve2book which stores the pairs.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!