Android - 绿道多重交易

时间:2015-09-05 11:32:31

标签: java android sqlite greendao

我在greendao的多笔交易中遇到了一些问题 例如,我已经有两个名为book和type_book的表。

我已经有这样的代码:

    SQLiteDatabase db = bookMasterDao.getDatabase();
    db.beginTransaction();

    try {
        bookMasterDao.insert(bookMaster);
        idBook = bookMaster.getId().intValue();
        db.setTransactionSuccessful();
    } catch (Exception ex) {
        System.out.println("Error insert book master " + ex);
    } finally {
        db.endTransaction();
    }



    SQLiteDatabase dbTypeBook = typeBookMasterDao.getDatabase();
    dbTypeBook.beginTransaction();

    try {
        typeBookMasterDao.insert(bookMaster);
        dbTypeBook.setTransactionSuccessful();
    } catch (Exception ex) {
        System.out.println("Error insert type book" + ex);
    } finally {
        dbTypeBook.endTransaction();
    }

我想如果事务类型书故障插入,事务簿主要回滚我的意思是取消插入数据书主。如何进行这样的交易?

任何想法,参考和示例都非常有用,谢谢。

1 个答案:

答案 0 :(得分:3)

我认为你误解了原则。尝试创建db,启动事务,用daoMaster包装数据库,使用session进行插入,然后设置事务成功。看看代码。

SQLiteDatabase db = openOrCreateDatabase("db", MODE_PRIVATE, null);
DaoMaster.createAllTables(db, true);

 db.beginTransaction();
 try {

  DaoMaster daoMaster = new DaoMaster(db);
  DaoSession daoSession = daoMaster.newSession();

  Book book = new Book();
  Book2 book2 = new Book2();

  //insert on specific session
  daoSession.getBookDao().insert(book);

  //set some relation to inserted book
  book2.setBook(book);

  //if this fails, book and book2 won't be in db
  //insert withou specific session
  daoSession.insert(book2); 

  db.setTransactionSuccessful();
} catch (Exception ex) {
    ex.printStackTrace();
} finally {
    db.endTransaction();
    db.close();
}