Mybaties自定義sql攔截器

第一步、編寫基礎類

public class Common {
    private int pagesize;
    private int pageid;
    private int pagebegin;
    private int count;
    //省略 get set 
}

第二步、實體類須要繼承基礎類

package lqb.bean;

public class User extends Common{

    private String id;
    private String name;
    private String t1;
    private String t2;
    private String t3;

 //省略get set   
}

 

第三步、攔截mybaties執行語句

package lqb.interceptor;

import java.util.Properties;
import org.apache.ibatis.executor.resultset.ResultSetHandler;  
import org.apache.ibatis.executor.statement.StatementHandler;  
import org.apache.ibatis.mapping.BoundSql;  
import org.apache.ibatis.mapping.MappedStatement;  
import org.apache.ibatis.plugin.*;  
import org.apache.ibatis.reflection.MetaObject;  
import org.apache.ibatis.reflection.SystemMetaObject;  
import java.sql.*;  
import lqb.bean.Common;

@Intercepts({
     @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class}),  
     @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
})  
public class PageInterceptor implements Interceptor {  
  
    private static final String SELECT_ID="selectpage";


    //插件運行的代碼,它將代替原有的方法
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("PageInterceptor -- intercept");
        
        
        if (invocation.getTarget() instanceof StatementHandler) {  
            StatementHandler statementHandler = (StatementHandler) invocation.getTarget();  
            MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);  
            MappedStatement mappedStatement=(MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
            String selectId=mappedStatement.getId();
            
            if(SELECT_ID.equals(selectId.substring(selectId.lastIndexOf(".")+1).toLowerCase())){
                BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");  
                // 分頁參數做爲參數對象parameterObject的一個屬性  
                String sql = boundSql.getSql();
                Common co=(Common)(boundSql.getParameterObject());
                
                // 重寫sql  
                String countSql=concatCountSql(sql);
                String pageSql=concatPageSql(sql,co);
                
                System.out.println("重寫的 count  sql        :"+countSql);
                System.out.println("重寫的 select sql        :"+pageSql);
                
                Connection connection = (Connection) invocation.getArgs()[0];  
                
                PreparedStatement countStmt = null;  
                ResultSet rs = null;  
                int totalCount = 0;  
                try { 
                    countStmt = connection.prepareStatement(countSql);  
                    rs = countStmt.executeQuery();  
                    if (rs.next()) {  
                        totalCount = rs.getInt(1);  
                    } 
                    
                } catch (SQLException e) {  
                    System.out.println("Ignore this exception"+e);  
                } finally {  
                    try {  
                        rs.close();  
                        countStmt.close();  
                    } catch (SQLException e) {  
                        System.out.println("Ignore this exception"+ e);  
                    }  
                }  
                
                metaStatementHandler.setValue("delegate.boundSql.sql", pageSql);            
              
                //綁定count
                co.setCount(totalCount);
            }
        } 
        
        return invocation.proceed();
    }
    
    /**
     * 攔截類型StatementHandler 
     */
    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {  
            return Plugin.wrap(target, this);  
        } else {  
            return target;  
        }  
    }
    
    @Override
    public void setProperties(Properties properties) {
        
    }  
    
    
    public String concatCountSql(String sql){
        StringBuffer sb=new StringBuffer("select count(*) from ");
        sql=sql.toLowerCase();
        
        if(sql.lastIndexOf("order")>sql.lastIndexOf(")")){
            sb.append(sql.substring(sql.indexOf("from")+4, sql.lastIndexOf("order")));
        }else{
            sb.append(sql.substring(sql.indexOf("from")+4));
        }
        return sb.toString();
    }
    
    public String concatPageSql(String sql,Common co){
        StringBuffer sb=new StringBuffer();
        sb.append(sql);
        sb.append(" limit ").append(co.getPagebegin()).append(" , ").append(co.getPagesize());
        return sb.toString();
    }
    
    public void setPageCount(){
        
    }
    
}

 

第四步、測試

User u=new User();
u.setPagebegin(2);
u.setPagesize(3);
List<User> list=userService.selectPage(u);
System.out.println(list.size());
System.out.println("-u.getCount()------"+u.getCount());

 

第五步、mybaties-config.xml配置

<plugins>  
    <plugin interceptor="lqb.interceptor.PageInterceptor"/>
</plugins>
相關文章
相關標籤/搜索