ORM框架

1.mybatis
可以通过拦截的方式处理问题,可以拦截请求sql使用jsqlparser解析sql获取参数字段

com.github.jsqlparser
jsqlparser
3.1

拦截请求:
@Intercepts({
@Signature(type = StatementHandler.class, method = "parameterize", args = Statement.class)
})

@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object target = realTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(target);
    String sql = (String) metaObject.getValue("delegate.boundSql.sql");
    List parameterMappings = (List) metaObject.getValue("delegate.boundSql.parameterMappings");
    Object parameterObject = metaObject.getValue("delegate.boundSql.parameterObject");
    final Object returnObj = invocation.proceed();
    return returnObj;
}

private static  T realTarget(Object target) {
    if (Proxy.isProxyClass(target.getClass())) {
        MetaObject metaObject = SystemMetaObject.forObject(target);
        return realTarget(metaObject.getValue("h.target"));
    } else {
        return (T) target;
    }
}

拦截还可以对返回结果字段进行处理:
@Intercepts({
@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class})
})

 @Override
public Object intercept(Invocation invocation) throws Throwable {
    Object target = realTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(target);
    MappedStatement ms = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    String sql = (String) metaObject.getValue("delegate.boundSql.sql");
    Configuration configuration = ms.getConfiguration();
    Collection resultMaps = configuration.getResultMaps();
    for (ResultMap r : resultMaps) {
        List resultMappings = r.getResultMappings();
        for (ResultMapping resultMapping : resultMappings) {
            resultMapping.getColumn();
            resultMapping.getProperty();
        }
        break;
    }
    final Object returnObj = invocation.proceed();
    return returnObj;
}
private static  T realTarget(Object target) {
    if (Proxy.isProxyClass(target.getClass())) {
        MetaObject metaObject = SystemMetaObject.forObject(target);
        return realTarget(metaObject.getValue("h.target"));
    } else {
        return (T) target;
    }
}

拦截器初始化可以利用config类 @Bean注解,手动进行new

另外可以使用handler来拦截返回数据或者请求数据进行处理:
@MappedJdbcTypes(value = {CLOB,CLOB,VARCHAR,LONGVARCHAR,NVARCHAR,NCHAR,NCLOB},includeNullJdbcType = true)
@MappedTypes(String.class)
public class MyStringTypeHandler extends BaseTypeHandler {}

其中includeNullJdbcType一定要有,否则不生效。
还需要配置handler路径mybatis.type-handlers-package: .****.

你可能感兴趣的:(ORM框架)