Android ormlite 开启事物

来源:互联网 发布:货代软件 编辑:程序博客网 时间:2024/05/23 00:13


用了 ormlite来做orm mapping,感觉挺好用的,就一直在项目中用了,在数据量小的时候挺好的万能的Dao接口的封装。让我用起来那是一个爽呀。。好日子总是的短暂的,服务器端的数据库一下子增加了800条数据!!用dao.createOrUpdate方法就比较的悲剧了,要执行40s!!实在是不能忍受了!!然后就很自然的想到要开启ormlite的事物了,可是上网上以找,找到一个,那里用发现不好使,话说还是要看源码比较的好。

找到了:

public Savepoint setSavePoint(String name) throws SQLException {try {db.beginTransaction();logger.trace("{}: save-point set with name {}", this, name);return new OurSavePoint(name);} catch (android.database.SQLException e) {throw SqlExceptionUtil.create("problems beginning transaction " + name, e);}}

看到:

db.beginTransaction();
是我想要的东西。

接下来还有:

public void commit(Savepoint savepoint) throws SQLException {try {db.setTransactionSuccessful();db.endTransaction();if (savepoint == null) {logger.trace("{}: transaction is successfuly ended", this);} else {logger.trace("{}: transaction {} is successfuly ended", this, savepoint.getSavepointName());}} catch (android.database.SQLException e) {throw SqlExceptionUtil.create("problems commiting transaction " + savepoint.getSavepointName(), e);}}

public void rollback(Savepoint savepoint) throws SQLException {try {// no setTransactionSuccessful() means it is a rollbackdb.endTransaction();if (savepoint == null) {logger.trace("{}: transaction is ended, unsuccessfuly", this);} else {logger.trace("{}: transaction {} is ended, unsuccessfuly", this, savepoint.getSavepointName());}} catch (android.database.SQLException e) {throw SqlExceptionUtil.create("problems rolling back transaction " + savepoint.getSavepointName(), e);}

看到这个写个方法,问题就基本上解决了。


AndroidDatabaseConnection connection = null;String pointName = "pointName";Savepoint savepoint = null;try{DebugTool.info ( "@@@@@@@@@@@@@@@@@@@@updateFooodTable= " + CommonUtil.getCurrentTime () );// // beging transaction connection = new AndroidDatabaseConnection ( BaseApplication.SQLiteAccess ().getHelper ( BaseApplication.mAppContext ).getWritableDatabase () , true );//connection.setAutoCommit ( false );dao.setAutoCommit ( connection , false );//dao.startThreadConnection (); savepoint = connection.setSavePoint ( pointName );for ( Food food : foodList ){try{dao.createOrUpdate ( food );}catch ( SQLException e ){DebugTool.info ( "<!=============updateFooodTable===========SQLException============>" );}catch ( Exception e ){DebugTool.info ( "<!=============updateFooodTable===========Exception================>" );}} ///foodcookmethods//connection.commit ( null );//dao.commit ( connection );connection.commit ( savepoint );DebugTool.info ( "@@@@@@@@@@@@@@@@@@@@updateFooodTable= " + CommonUtil.getCurrentTime () );}catch ( SQLException e ){DebugTool.error ( "<!===updateFooodTable====>" ,e);try{connection.rollback ( savepoint );}catch ( SQLException e1 ){DebugTool.error ( "<!===updateFooodTable++rollback=SQLException===>" ,e1);}}