Prototype功能預覽二:兩個註解實現數據庫批處理

框架整體介紹:http://blog.csdn.net/flyxxxxx/article/category/7055640

對此框架有興趣或想參與開發的請加QQ羣:255195191


以下演示一段基於Prototype框架數據庫批處理的例子:

@Prototype //此註解標識這是一個基於原型模式的類
public class BatchBusiness {

    private List<Dict> inserted = new ArrayList<>();//這是要準備插入的數據
    private List<Dict> updated = new ArrayList<>();//這是要準備更新的數據

    @Transactional   //使用Spring的此註解開啓事務
    @Batch(value = { "update", "insert" }, after = true) //在execute方法執行完成後執行批處理方法update和insert
    public void execute() {
        updated.add(new Dict(1, "Item1"));//這裏爲了測試,準備一些數據
        updated.add(new Dict(2, "Item2"));
        inserted.add(new Dict("Item3"));
        inserted.add(new Dict("Item4"));
    }

    @BatchSql("update sys_dict set name=? where id=?")  //批處理用的SQL語句
    CollectionIterator<?> update() {
        return new CollectionIterator<Dict>(updated) {  //對批處理的數據進行循環

            @Override
            public Object[] next(Dict t) {
                return new Object[] { t.getName(), t.getId() };  //給SQL按順序提供參數
            }

        };
    }

    @BatchSql("insert into sys_dict(name) values(?)")
    CollectionIterator<?> insert() {
        return new InsertIterator<Dict>(inserted) {  //與上一個方法不同的是這裏需要取回插入數據的id值

            @Override
            public Object[] next(Dict t) {
                return new Object[] { t.getName() };  //給SQL按順序提供參數
            }

        };
    }
}

測試代碼:

public void test(){

  BatchBusiness busi=new BatchBusiness();

  busi.execute();//此方法開啓事務和批處理

}

以上代碼,當調用execute方法時:

1、Trancacational註解開啓事務

2、執行execute方法準備測試用的數據

3、執行方法update前,準備PreparedStatement,調用update獲得數據的循環,循環數據過程中,調用next方法注入批處理的參數,完成此項批處理

4、同樣執行方法insert並在批量提交後獲取每一行數據的id值

5、完成批處理,提交事務


使用Prototype框架,程序員無需關心複雜的jdbc操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章