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的攔截器比理解它的要快。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM