问题
I have some problem for multiple transaction in greendao example i already have two table with name book and type_book.
i already have code like this :
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();
}
I want if transaction type book failure insert , transaction book master rollback i mean cancel insert data book master. How to make transaction like that?
any idea, reference and example very help thank you.
回答1:
I think you misunderstood the principe. Try create db, start transaction, wrap the databse with daoMaster, use session for inserting, then set transaction successfull. Look at the code.
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();
}
来源:https://stackoverflow.com/questions/32412573/android-green-dao-multiple-transaction