mybatis 自定义 拦截器

转载的。。。。。http://zhenghuazhi.iteye.com/blog/1468992

页面输入:男,数据库保存male,女,数据库保存为female。

使用interceptor,typeHandler

Java代码   收藏代码
  1. package cn.dcr.mybatis.util;  
  2.   
  3. import java.util.Properties;  
  4.   
  5. import org.apache.ibatis.executor.Executor;  
  6. import org.apache.ibatis.mapping.MappedStatement;  
  7. import org.apache.ibatis.plugin.Interceptor;  
  8. import org.apache.ibatis.plugin.Intercepts;  
  9. import org.apache.ibatis.plugin.Invocation;  
  10. import org.apache.ibatis.plugin.Plugin;  
  11. import org.apache.ibatis.plugin.Signature;  
  12. import org.apache.ibatis.session.ResultHandler;  
  13. import org.apache.ibatis.session.RowBounds;  
  14.   
  15. import com.test.pojos.User;  
  16.   
  17. @Intercepts({  
  18.         @Signature(type = Executor.class, method = "update", args = {  
  19.                 MappedStatement.class, Object.class }),  
  20.         @Signature(type = Executor.class, method = "query", args = {  
  21.                 MappedStatement.class, Object.class, RowBounds.class,  
  22.                 ResultHandler.class }) })  
  23. public class MyInterceptor implements Interceptor {  
  24.   
  25.     private static final String R_FEMALE = "女";  
  26.   
  27.     private static final String R_MALE = "男";  
  28.   
  29.     private static final String FEMALE = "female";  
  30.   
  31.     private static final String MALE = "male";  
  32.     private Properties properties;  
  33.   
  34.     /* 
  35.      * (non-Javadoc) 
  36.      *  
  37.      * @see 
  38.      * org.apache.ibatis.plugin.Interceptor#intercept(org.apache.ibatis.plugin 
  39.      * .Invocation) 
  40.      */  
  41.     public Object intercept(Invocation invocation) throws Throwable {  
  42.   
  43.         MappedStatement mappedStatement = (MappedStatement) invocation  
  44.                 .getArgs()[0];  
  45.         String sqlId = mappedStatement.getId();  
  46.         String namespace = sqlId.substring(0, sqlId.indexOf('.'));  
  47.         Executor exe = (Executor) invocation.getTarget();  
  48.         String methodName = invocation.getMethod().getName();  
  49.   
  50.         if (methodName.equals("query")) {  
  51.                 Object parameter = invocation.getArgs()[1];  
  52.                 RowBounds rowBounds = (RowBounds) invocation.getArgs()[2];  
  53.                    
  54.         }  
  55.         else if(methodName.equals("update")){  
  56.             Object parameter = invocation.getArgs()[1];  
  57.             if(parameter instanceof User)  
  58.                 ((User)parameter).setGender(saveValueToDb(((User)parameter).getGender()));  
  59.               
  60.         }  
  61.         return invocation.proceed();  
  62.   
  63.     }  
  64.   
  65.     /* 
  66.      * (non-Javadoc) 
  67.      *  
  68.      * @see org.apache.ibatis.plugin.Interceptor#plugin(java.lang.Object) 
  69.      */  
  70.     public Object plugin(Object target) {  
  71.         return Plugin.wrap(target, this);  
  72.     }  
  73.   
  74.     /* 
  75.      * (non-Javadoc) 
  76.      *  
  77.      * @see 
  78.      * org.apache.ibatis.plugin.Interceptor#setProperties(java.util.Properties) 
  79.      */  
  80.     public void setProperties(Properties properties) {  
  81.         this.properties = properties;  
  82.   
  83.     }  
  84.     /**插入数据库 
  85.      * @param value 
  86.      * @return 
  87.      */  
  88.     private String saveValueToDb(String value) {  
  89.         if (value.equals(R_FEMALE)) {  
  90.             return FEMALE;  
  91.         } else if (value.equals(R_MALE)) {  
  92.             return MALE;  
  93.         } else {  
  94.             throw new IllegalArgumentException("数据库异常!" + value);  
  95.         }  
  96.     }  
  97.   
  98. }  

 

Java代码   收藏代码
  1.    

 

Java代码   收藏代码
  1. @Intercepts({  
  2.         @Signature(type = Executor.class, method = "update", args = {  
  3.                 MappedStatement.class, Object.class }),  
  4.         @Signature(type = Executor.class, method = "query", args = {  
  5.                 MappedStatement.class, Object.class, RowBounds.class,  
  6.                 ResultHandler.class }) })  

 mybatis 拦截器好像只能使用注解,而且对于接口Executor,method只定义了update,query,flushStatements,commit,rollback,createCacheKey,isCached,clearLocalCache,deferLoad,getTransaction,close,isClosed这几个方法,没有delete和insert方法。

具体详见:

Java代码   收藏代码
  1. package org.apache.ibatis.executor;  
  2.   
  3. import org.apache.ibatis.cache.CacheKey;  
  4. import org.apache.ibatis.mapping.MappedStatement;  
  5. import org.apache.ibatis.reflection.MetaObject;  
  6. import org.apache.ibatis.session.ResultHandler;  
  7. import org.apache.ibatis.session.RowBounds;  
  8. import org.apache.ibatis.transaction.Transaction;  
  9.   
  10. import java.sql.SQLException;  
  11. import java.util.List;  
  12.   
  13. public interface Executor {  
  14.   
  15.   ResultHandler NO_RESULT_HANDLER = null;  
  16.   
  17.   int update(MappedStatement ms, Object parameter) throws SQLException;  
  18.   
  19.   List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException;  
  20.   
  21.   List<BatchResult> flushStatements() throws SQLException;  
  22.   
  23.   void commit(boolean required) throws SQLException;  
  24.   
  25.   void rollback(boolean required) throws SQLException;  
  26.   
  27.   CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds);  
  28.   
  29.   boolean isCached(MappedStatement ms, CacheKey key);  
  30.   
  31.   void clearLocalCache();  
  32.   
  33.   void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key);  
  34.   
  35.   Transaction getTransaction();  
  36.   
  37.   void close(boolean forceRollback);  
  38.     
  39.   boolean isClosed();  
  40.   
  41. }  

    当我疑惑为什么mybatis没有在insert和delete的时候拦截呢?

看到了mybatis googleCode上的issue16。

Issue 16:Update interceptor (plugin) fires for inserts
Html代码   收藏代码
  1. Reporter:    Eli Kizhnerman  
  2.   
  3. The iBatis plugin does not seem to be resolving the target methods to  
  4. intercept properly. An interceptor that is defined to intercept only  
  5. updates is also executed on inserts.  
  6.   
  7. I have the following definition:  
  8. @Intercepts({@Signature(  
  9.         type=Executor.class,  
  10.         method="update",  
  11.         args={MappedStatement.class,Object.class})})  
  12. public class UpdateInterceptor implements Interceptor {  
  13. ...  
  14. }  
  15.   
  16. In Plugin.invoke you have the following code:  
  17.   
  18.       Set<Methodmethods = signatureMap.get(method.getDeclaringClass());  
  19.       if (methods != null && methods.contains(method)) {  
  20.         return interceptor.intercept(new Invocation(target, method, args));  
  21.       }  
  22.   
  23. DefaultSqlSession.insert internally calls an update method:  
  24.   
  25.   public int insert(String statement, Object parameter) {  
  26.     return update(statement, parameter);  
  27.   }  
  28.   
  29. I suspect that the Method that is being passed to plugin.invoke is actually  
  30. the update method and therefore the interceptor is executed.   

  原来在DefaultSqlSession的insert,delete方法也是调用了update方法。

Java代码   收藏代码
  1. public int insert(String statement, Object parameter) {  
  2.     return update(statement, parameter);  
  3.   }  

  

Java代码   收藏代码
  1. public int delete(String statement, Object parameter) {  
  2.     return update(statement, wrapCollection(parameter));  
  3.   }  

   mybatis太不厚道了,它的文档也没有具体的说明。

    有人提出这是个bug,不过mybatis没有承认。

Java代码   收藏代码
  1. Clinton Begin added a comment - 10/Dec/09 03:58 PM  
  2. Executor only has update and query methods. Thus inserts and deletes are also  
  3. considered updates. It sounds like to do what you want, we need another interception  
  4. point, at the session level. You can do so right now with a proxy class between the  
  5. SqlSession interface and the default implementation.  
  6. [ Show » ]  
  7. Clinton Begin added a comment - 10/Dec/09 03:58 PM Executor only has update and query  
  8. methods. Thus inserts and deletes are also considered updates. It sounds like to do  
  9. what you want, we need another interception point, at the session level. You can do  
  10. so right now with a proxy class between the SqlSession interface and the default  
  11. implementation.  
  12.   
  13. [ Permalink | Delete | « Hide ]  
  14. Eli Kizhnerman added a comment - 11/Dec/09 12:28 PM  
  15. This is not working the way I expected it but that it is not a bug. I can get what I  
  16. need from the MappedStatement SqlCommandType.  

 

Java代码   收藏代码
  1. package cn.dcr.mybatis.util;  
  2.   
  3. import java.sql.CallableStatement;  
  4. import java.sql.PreparedStatement;  
  5. import java.sql.ResultSet;  
  6. import java.sql.SQLException;  
  7.   
  8. import org.apache.ibatis.type.BaseTypeHandler;  
  9. import org.apache.ibatis.type.JdbcType;  
  10.   
  11. /**自定义typeHandler<br/> 
  12.  * 1 插入数据库,男转为male 
  13.  * 2 查询,maile转为男 
  14.  * @author Administrator 
  15.  * 
  16.  */  
  17. public class GenderTypeHandlerCallback extends BaseTypeHandler<String> {  
  18.   
  19.     private static final String R_FEMALE = "女";  
  20.   
  21.     private static final String R_MALE = "男";  
  22.   
  23.     private static final String FEMALE = "female";  
  24.   
  25.     private static final String MALE = "male";  
  26.   
  27.     @Override  
  28.     public String getNullableResult(CallableStatement cs, int columnIndex)  
  29.             throws SQLException {  
  30.   
  31.         return cs.getString(columnIndex);  
  32.     }  
  33.   
  34.     @Override  
  35.     public String getNullableResult(ResultSet rs, String columnName)  
  36.             throws SQLException {  
  37.         String t = rs.getString(columnName);  
  38.         return converSex(t);  
  39.     }  
  40.   
  41.     @Override  
  42.     public void setNonNullParameter(PreparedStatement preparedStatement, int i,  
  43.             String str, JdbcType jdbcType) throws SQLException {  
  44.   
  45.         preparedStatement.setString(i, saveValueToDb(str));  
  46.   
  47.     }  
  48.   
  49.     /**插入数据库 
  50.      * @param value 
  51.      * @return 
  52.      */  
  53.     private String saveValueToDb(String value) {  
  54.         if (value.equals(R_FEMALE)) {  
  55.             return FEMALE;  
  56.         } else if (value.equals(R_MALE)) {  
  57.             return MALE;  
  58.         } else {  
  59.             throw new IllegalArgumentException("数据库异常!" + value);  
  60.         }  
  61.     }  
  62.       
  63.     /** 从数据库读出 
  64.      * @param value 
  65.      * @return 
  66.      */  
  67.     private String converSex(String value){  
  68.         if (value.equals(FEMALE)) {  
  69.             return R_FEMALE;  
  70.         } else if (value.equals(MALE)) {  
  71.             return R_MALE;  
  72.         } else {  
  73.             throw new IllegalArgumentException("数据库异常!" + value);  
  74.         }  
  75.     }  
  76.   
  77. }  

  在自定义typeHandler的getNullableResult方法中调整自己的结果集,可以说是在sql执行后,IOC的理论叫后置通知,interceptor应该是前置通知。

Java代码   收藏代码
  1. @Override  
  2.     public String getNullableResult(ResultSet rs, String columnName)  
  3.             throws SQLException {  
  4.         String t = rs.getString(columnName);  
  5.         return converSex(t);  
  6.     }  

 在typeHandler的setNonNullParameter,应该是参数传入前转换参数的功能,但是实际操作中没有被调用,不知道为什么。

Java代码   收藏代码
  1. @Override  
  2.     public void setNonNullParameter(PreparedStatement preparedStatement, int i,  
  3.             String str, JdbcType jdbcType) throws SQLException {  
  4.   
  5.         preparedStatement.setString(i, saveValueToDb(str));  
  6.   
  7.     }  

 以上是对mybatis 的切入点的实践。总体感觉和struts2的拦截器比,还有差距,至少我理解struts2的拦截器比理解它的要快。

转载于:https://www.cnblogs.com/whm-blog/p/7337918.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值