Example usage for org.apache.ibatis.reflection SystemMetaObject forObject

List of usage examples for org.apache.ibatis.reflection SystemMetaObject forObject

Introduction

In this page you can find the example usage for org.apache.ibatis.reflection SystemMetaObject forObject.

Prototype

public static MetaObject forObject(Object object) 

Source Link

Usage

From source file:cn.myblog.uitl.MybatisPageHelper.PageHelper.java

License:Open Source License

@Override
public Object intercept(Invocation invocation) throws Throwable {
    final Object[] args = invocation.getArgs();
    RowBounds rowBounds = (RowBounds) args[2];
    if (localPage.get() == null && rowBounds == RowBounds.DEFAULT) {
        return invocation.proceed();
    } else {/*from   w  w  w .jav a  2 s  .  c  o m*/
        //RowBounds-?Mybatis
        args[2] = RowBounds.DEFAULT;
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = ms.getBoundSql(parameterObject);

        //?
        Page page = localPage.get();
        //??
        localPage.remove();

        if (page == null) {
            if (offsetAsPageNum) {
                page = new Page(rowBounds.getOffset(), rowBounds.getLimit(),
                        rowBoundsWithCount ? Page.SQL_COUNT : Page.NO_SQL_COUNT);
            } else {
                page = new Page(rowBounds, rowBoundsWithCount ? Page.SQL_COUNT : Page.NO_SQL_COUNT);
            }
        }
        MappedStatement qs = newMappedStatement(ms, new BoundSqlSqlSource(boundSql));
        //?MappedStatement?qs?
        args[0] = qs;
        MetaObject msObject = SystemMetaObject.forObject(qs);
        String sql = (String) msObject.getValue("sqlSource.boundSql.sql");
        //?total??count
        if (page.getTotal() > Page.NO_SQL_COUNT) {
            //count - ?sql
            msObject.setValue("sqlSource.boundSql.sql", getCountSql(sql));
            //
            Object result = invocation.proceed();
            int totalCount = (Integer) ((List) result).get(0);
            page.setTotal(totalCount);
            int totalPage = totalCount / page.getPageSize() + ((totalCount % page.getPageSize() == 0) ? 0 : 1);
            page.setPages(totalPage);
            //sql - ?sql
            msObject.setValue("sqlSource.boundSql.sql", getPageSql(sql, page));
            //??
            msObject.setValue("resultMaps", ms.getResultMaps());
            //
            result = invocation.proceed();
            //?
            page.addAll((List) result);
            //
            return page;
        } else {
            //sql - ?sql
            msObject.setValue("sqlSource.boundSql.sql", getPageSql(sql, page));
            //??
            msObject.setValue("resultMaps", ms.getResultMaps());
            //
            Object result = invocation.proceed();
            //?
            page.addAll((List) result);
            //
            return page;
        }
    }
}

From source file:com.appleframework.orm.mybatis.pagehelper.parser.impl.AbstractParser.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map<String, Object> processParameter(MappedStatement ms, Object parameterObject,
        BoundSql boundSql) {//from   w  ww .jav a 2s .  c om
    Map<String, Object> paramMap = null;
    if (parameterObject == null) {
        paramMap = new HashMap<String, Object>();
    } else if (parameterObject instanceof Map) {
        //???Map
        paramMap = new HashMap<String, Object>();
        paramMap.putAll((Map) parameterObject);
    } else {
        paramMap = new HashMap<String, Object>();
        //?sql??ParameterMapping?getter
        //TypeHandlerRegistry???
        boolean hasTypeHandler = ms.getConfiguration().getTypeHandlerRegistry()
                .hasTypeHandler(parameterObject.getClass());
        MetaObject metaObject = SystemMetaObject.forObject(parameterObject);
        //??MyProviderSqlSource?
        if (ms.getSqlSource() instanceof PageProviderSqlSource) {
            paramMap.put(PROVIDER_OBJECT, parameterObject);
        }
        if (!hasTypeHandler) {
            for (String name : metaObject.getGetterNames()) {
                paramMap.put(name, metaObject.getValue(name));
            }
        }
        //????
        if (boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0) {
            for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
                String name = parameterMapping.getProperty();
                if (!name.equals(PAGEPARAMETER_FIRST) && !name.equals(PAGEPARAMETER_SECOND)
                        && paramMap.get(name) == null) {
                    if (hasTypeHandler || parameterMapping.getJavaType().equals(parameterObject.getClass())) {
                        paramMap.put(name, parameterObject);
                        break;
                    }
                }
            }
        }
    }
    //?
    paramMap.put(ORIGINAL_PARAMETER_OBJECT, parameterObject);
    return paramMap;
}

From source file:com.appleframework.orm.mybatis.pagehelper.sqlsource.PageDynamicSqlSource.java

License:Open Source License

public PageDynamicSqlSource(DynamicSqlSource sqlSource) {
    MetaObject metaObject = SystemMetaObject.forObject(sqlSource);
    this.configuration = (Configuration) metaObject.getValue("configuration");
    this.rootSqlNode = (SqlNode) metaObject.getValue("rootSqlNode");
}

From source file:com.appleframework.orm.mybatis.pagehelper.sqlsource.PageProviderSqlSource.java

License:Open Source License

public PageProviderSqlSource(ProviderSqlSource provider) {
    MetaObject metaObject = SystemMetaObject.forObject(provider);
    this.sqlSourceParser = (SqlSourceBuilder) metaObject.getValue("sqlSourceParser");
    this.providerType = (Class<?>) metaObject.getValue("providerType");
    this.providerMethod = (Method) metaObject.getValue("providerMethod");
    this.configuration = (Configuration) metaObject.getValue("sqlSourceParser.configuration");
    try {//w  ww .  j av  a 2  s  .  co m
        //3.3.1??
        this.providerTakesParameterObject = (Boolean) metaObject.getValue("providerTakesParameterObject");
    } catch (ReflectionException e) {
        //3.4.0+#102 by Ian Lim
        providerMethodArgumentNames = (String[]) metaObject.getValue("providerMethodArgumentNames");
    }
}

From source file:com.appleframework.orm.mybatis.pagehelper.SqlUtil.java

License:Open Source License

/**
 * ??//from   w  ww  .  ja  v a2s.c  o  m
 *
 * @param params
 * @return
 */
public static <T> Page<T> getPageFromObject(Object params) {
    int pageNum;
    int pageSize;
    MetaObject paramsObject = null;
    if (params == null) {
        throw new NullPointerException("??!");
    }
    if (hasRequest && requestClass.isAssignableFrom(params.getClass())) {
        try {
            paramsObject = SystemMetaObject.forObject(getParameterMap.invoke(params, new Object[] {}));
        } catch (Exception e) {
            //
        }
    } else {
        paramsObject = SystemMetaObject.forObject(params);
    }
    if (paramsObject == null) {
        throw new NullPointerException("??!");
    }
    Object orderBy = getParamValue(paramsObject, "orderBy", false);
    boolean hasOrderBy = false;
    if (orderBy != null && orderBy.toString().length() > 0) {
        hasOrderBy = true;
    }
    try {
        Object _pageNum = getParamValue(paramsObject, "pageNum", hasOrderBy ? false : true);
        Object _pageSize = getParamValue(paramsObject, "pageSize", hasOrderBy ? false : true);
        if (_pageNum == null || _pageSize == null) {
            return new Page();
        }
        pageNum = Integer.parseInt(String.valueOf(_pageNum));
        pageSize = Integer.parseInt(String.valueOf(_pageSize));
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("???!");
    }
    Page page = new Page(pageNum, pageSize);
    //count
    Object _count = getParamValue(paramsObject, "count", false);
    if (_count != null) {
        page.setCount(Boolean.valueOf(String.valueOf(_count)));
    }
    //??
    Object reasonable = getParamValue(paramsObject, "reasonable", false);
    if (reasonable != null) {
        page.setReasonable(Boolean.valueOf(String.valueOf(reasonable)));
    }
    //
    Object pageSizeZero = getParamValue(paramsObject, "pageSizeZero", false);
    if (pageSizeZero != null) {
        page.setPageSizeZero(Boolean.valueOf(String.valueOf(pageSizeZero)));
    }
    return page;
}

From source file:com.appleframework.orm.mybatis.pagehelper.SqlUtil.java

License:Open Source License

/**
 * SqlSource//from w ww.j ava  2s .  c  o m
 *
 * @param ms
 * @throws Throwable
 */
public void processMappedStatement(MappedStatement ms) throws Throwable {
    SqlSource sqlSource = ms.getSqlSource();
    MetaObject msObject = SystemMetaObject.forObject(ms);
    SqlSource pageSqlSource;
    if (sqlSource instanceof StaticSqlSource) {
        pageSqlSource = new PageStaticSqlSource((StaticSqlSource) sqlSource);
    } else if (sqlSource instanceof RawSqlSource) {
        pageSqlSource = new PageRawSqlSource((RawSqlSource) sqlSource);
    } else if (sqlSource instanceof ProviderSqlSource) {
        pageSqlSource = new PageProviderSqlSource((ProviderSqlSource) sqlSource);
    } else if (sqlSource instanceof DynamicSqlSource) {
        pageSqlSource = new PageDynamicSqlSource((DynamicSqlSource) sqlSource);
    } else {
        throw new RuntimeException("?[" + sqlSource.getClass() + "]SqlSource");
    }
    msObject.setValue("sqlSource", pageSqlSource);
    //count??CountMS
    msCountMap.put(ms.getId(), MSUtils.newCountMappedStatement(ms));
}

From source file:com.baomidou.mybatisplus.plugins.CachePaginationInterceptor.java

License:Apache License

/**
 * Physical Pagination Interceptor for all the queries with parameter
 * {@link org.apache.ibatis.session.RowBounds}
 *///from  w  ww . ja  v a 2s.c  om
public Object intercept(Invocation invocation) throws Throwable {

    Object target = invocation.getTarget();
    if (target instanceof StatementHandler) {
        StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
        RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");

        if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
            return invocation.proceed();
        }
        BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
        String originalSql = boundSql.getSql();

        if (rowBounds instanceof Pagination) {
            Pagination page = (Pagination) rowBounds;
            boolean orderBy = true;
            if (page.isSearchCount()) {
                CountOptimize countOptimize = SqlUtils.getCountOptimize(originalSql, optimizeType, dialectType,
                        page.isOptimizeCount());
                orderBy = countOptimize.isOrderBy();
            }
            String buildSql = SqlUtils.concatOrderBy(originalSql, page, orderBy);
            originalSql = DialectFactory.buildPaginationSql(page, buildSql, dialectType, dialectClazz);
        } else {
            // support physical Pagination for RowBounds
            originalSql = DialectFactory.buildPaginationSql(rowBounds, originalSql, dialectType, dialectClazz);
        }

        metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
        metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
        metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
    } else {
        RowBounds rowBounds = (RowBounds) invocation.getArgs()[2];
        if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
            return invocation.proceed();
        }
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Executor executor = (Executor) invocation.getTarget();
        Connection connection = executor.getTransaction().getConnection();
        Object parameterObject = invocation.getArgs()[1];
        BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
        String originalSql = boundSql.getSql();
        if (rowBounds instanceof Pagination) {
            Pagination page = (Pagination) rowBounds;
            if (page.isSearchCount()) {
                CountOptimize countOptimize = SqlUtils.getCountOptimize(originalSql, optimizeType, dialectType,
                        page.isOptimizeCount());
                super.queryTotal(countOptimize.getCountSQL(), mappedStatement, boundSql, page, connection);
                if (page.getTotal() <= 0) {
                    return invocation.proceed();
                }
            }
        }
    }
    return invocation.proceed();
}

From source file:com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor.java

License:Apache License

public Object intercept(Invocation invocation) throws Exception {
    StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
    // ?UPDATE?/*from   w w w .  j  av a 2s.c o m*/
    MappedStatement ms = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    if (!ms.getSqlCommandType().equals(SqlCommandType.UPDATE)) {
        return invocation.proceed();
    }
    BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
    // ?,?version?
    Class<?> parameterClass = ms.getParameterMap().getType();
    LockerCache lockerCache = versionCache.get(parameterClass);
    if (lockerCache != null) {
        if (lockerCache.lock) {
            processChangeSql(ms, boundSql, lockerCache);
        }
    } else {
        Field versionField = getVersionField(parameterClass);
        if (versionField != null) {
            Class<?> fieldType = versionField.getType();
            if (!typeHandlers.containsKey(fieldType)) {
                throw new TypeException(
                        "????" + fieldType.getName() + ",");
            }
            final TableField tableField = versionField.getAnnotation(TableField.class);
            String versionColumn = versionField.getName();
            if (tableField != null) {
                versionColumn = tableField.value();
            }
            LockerCache lc = new LockerCache(true, versionColumn, versionField, typeHandlers.get(fieldType));
            versionCache.put(parameterClass, lc);
            processChangeSql(ms, boundSql, lc);
        } else {
            versionCache.put(parameterClass, LockerCache.INSTANCE);
        }
    }
    return invocation.proceed();

}

From source file:com.baomidou.mybatisplus.plugins.PaginationInterceptor.java

License:Apache License

/**
 * Physical Pagination Interceptor for all the queries with parameter {@link org.apache.ibatis.session.RowBounds}
 *//*from ww  w  .j  a va2s  . c o m*/
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
    MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
    // ?SELECT?
    MappedStatement mappedStatement = (MappedStatement) metaStatementHandler
            .getValue("delegate.mappedStatement");
    if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
        return invocation.proceed();
    }
    RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");
    /* ??? */
    if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
        return invocation.proceed();
    }
    BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
    String originalSql = boundSql.getSql();
    Connection connection = (Connection) invocation.getArgs()[0];
    if (isDynamicDataSource()) {
        dialectType = JdbcUtils.getDbType(connection.getMetaData().getURL()).getDb();
    }
    if (rowBounds instanceof Pagination) {
        Pagination page = (Pagination) rowBounds;
        boolean orderBy = true;
        if (page.isSearchCount()) {
            CountOptimize countOptimize = SqlUtils.getCountOptimize(originalSql, optimizeType, dialectType,
                    page.isOptimizeCount());
            orderBy = countOptimize.isOrderBy();
            this.queryTotal(countOptimize.getCountSQL(), mappedStatement, boundSql, page, connection);
            if (page.getTotal() <= 0) {
                return invocation.proceed();
            }
        }
        String buildSql = SqlUtils.concatOrderBy(originalSql, page, orderBy);
        originalSql = DialectFactory.buildPaginationSql(page, buildSql, dialectType, dialectClazz);
    } else {
        // support physical Pagination for RowBounds
        originalSql = DialectFactory.buildPaginationSql(rowBounds, originalSql, dialectType, dialectClazz);
    }

    /*
       * <p> ? </p> <p> ???????</p>
     */
    metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
    metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
    metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
    return invocation.proceed();
}

From source file:com.baomidou.mybatisplus.plugins.PerformanceInterceptor.java

License:Apache License

public Object intercept(Invocation invocation) throws Throwable {
    Statement statement;//from   www . java 2s. co m
    Object firstArg = invocation.getArgs()[0];
    if (Proxy.isProxyClass(firstArg.getClass())) {
        statement = (Statement) SystemMetaObject.forObject(firstArg).getValue("h.statement");
    } else {
        statement = (Statement) firstArg;
    }
    try {
        statement.getClass().getDeclaredField("stmt");
        statement = (Statement) SystemMetaObject.forObject(statement).getValue("stmt.statement");
    } catch (Exception e) {
        // do nothing
    }
    String originalSql = statement.toString();
    int index = originalSql.indexOf(':');
    String sql = originalSql;
    if (index > 0) {
        sql = originalSql.substring(index + 1, originalSql.length());
    }
    long start = SystemClock.now();
    Object result = invocation.proceed();
    long end = SystemClock.now();
    long timing = end - start;
    String formatSql = SqlUtils.sqlFormat(sql, format);
    Object target = PluginUtils.realTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(target);
    MappedStatement ms = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    System.err.println(
            " Time" + timing + " ms" + " - ID" + ms.getId() + "\n Execute SQL" + formatSql + "\n");
    if (maxTime >= 1 && timing > maxTime) {
        throw new MybatisPlusException(" The SQL execution time is too large, please optimize ! ");
    }
    return result;
}