mybatis-sqlite

最近需要和移動端配置配合,將後臺的結果數據生成sqlite數據庫傳給移動端(因爲需要離線查看),所以配置信息的話需要同步存入sqlite。
1 創建和後臺一樣的表結構
2 做一個攔截器,只需要攔截StatementHandle 就可以了,僅處理增、刪、改操作,對於sqlite來說 ,批量插入時 ,需要去掉 from dual(我使用的是oracle),所以插入的時候 還要去掉from dual
3 在mybatis中,配置一個動態數據源,便於切換(可能特殊的需要處理了)及獲取
4 這裏遇到個問題,就是 我使用的是 sqlite-jdbc 驅動,但是使用最新的版本(3.19.3)及其它新版本時,出現 發佈找不到該驅動jar包,但是單元測試又通過的,有點暈~~ 後來找了個低版本(3.7.2)的驅動就可以了 ,不知道高版本做了什麼限制。。

好了 這樣就可以實現oracle和sqlite同步了!!

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MetaObject mb = SystemMetaObject.forObject(args[0]);
        MetaObject mbTarget = SystemMetaObject.forObject(invocation.getTarget());
        MappedStatement mappedStatement = (MappedStatement) mbTarget.getValue("delegate.mappedStatement");
        MetaObject mbStatement = SystemMetaObject.forObject(invocation.getTarget());
        BoundSql boundSql = (BoundSql) mbStatement.getValue("delegate.boundSql");
        excutorSqlite(invocation, mappedStatement, boundSql);
        return invocation.proceed();
    }
    private int excutorSqlite(Invocation invocation, MappedStatement mappedStatement, BoundSql boundSql)
            throws SQLException {
        int count = 0;
        String defaultSql = "";
        String sql = defaultSql = boundSql.getSql();
        MetaObject boundsqlMb = null;
        try {
//獲取sqlite數據源
            DataSource sqliteDataSourcce = DynamicDataSource.getSqliteDataSource();
            //獲取鏈接
            Connection conn = DataSourceUtils.getConnection(sqliteDataSourcce);

            if (mappedStatement.getSqlCommandType().equals(SqlCommandType.INSERT)) {
            //新增時去除from dual
                sql = sql.replaceAll("from dual", "");
                boundsqlMb = SystemMetaObject.forObject(boundSql);
                boundsqlMb.setValue("sql", sql);
            }
            PreparedStatement ps = conn.prepareStatement(sql);
            ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement,
                    boundSql.getParameterObject(), boundSql);
            parameterHandler.setParameters(ps);
            count = ps.executeUpdate();

        } catch (Exception e) {
            LogUtil.error("sqlite 執行報錯:" + e + "|sql:" + sql);

        }
        if (boundsqlMb != null) {
            boundsqlMb.setValue("sql", defaultSql);
        }
        return count;
    }
    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            MetaObject mb = SystemMetaObject.forObject(target);
            MappedStatement mappedStatement = (MappedStatement) mb.getValue("delegate.mappedStatement");
            if (Arrays.asList(SQLITE_SQLCOMMANDTYPE).contains(mappedStatement.getSqlCommandType())) {
                return Plugin.wrap(target, this);
            }
        }
        return target;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章