lMasterSparkl commented on issue #7703:
URL: 
https://github.com/apache/shardingsphere/issues/7703#issuecomment-1074955190


   > @lMasterSparkl Sorry, I'm not very familiar with JPA, this may require you 
to study how JPA is used. Looking forward to your good news.
   
   @strongduanmu @heqiao @sabz90 @qiuxiaotong2021
   now I used interceptor to changed update sql and add sharding column in  it 
here is the demo
   ```
   import lombok.extern.slf4j.Slf4j;
   import org.apache.commons.lang3.StringUtils;
   import org.hibernate.EmptyInterceptor;
   import java.util.HashMap;
   import java.util.Map;
   @Slf4j
   public class AutoAddDidInterceptor extends EmptyInterceptor {
   
       public static ThreadLocal<Map<String, String>> myTable = new 
ThreadLocal<>();
   
       public static void setInterceptorDid(String did){
           Map<String, String> map = new HashMap<>();
           map.put("did_update", did);
       }
       @Override
       public String onPrepareStatement(String sql) {
           log.debug("sql interceptor worked" );
           Map<String, String> map = myTable.get();
           if (map == null) {
               return sql;
           }
           String did = map.get("did_update");
           if (StringUtils.isEmpty(did) ) {
               return sql;
           }
           //judge update sql
           if(sql.startsWith("update")){
               String[] wheres = sql.split("where");
               StringBuffer stringBuffer = new StringBuffer();
               stringBuffer.append(wheres[0]).append(" where did = '"+did+"' 
and ").append(wheres[1]);
               log.warn("sql has been modify and now is 
{}",stringBuffer.toString());
               //clean threadLocal
               myTable.remove();
               return stringBuffer.toString();
           }else{
               return sql;
           }
       }
   
   }
   ```
   and config the interceptor in config file I'm use properties
   
   ```
   
spring.jpa.properties.hibernate.session_factory.session_scoped_interceptor=com.AutoAddDidInterceptor
   ```
   then use in business code like this
   ```
               AutoAddDidInterceptor.setInterceptorDid(post.getDid());
               postRepository.save(post);
   ```
   and in my test its already work to update data.
   
   but I have some Security question that if it might seen SQL injection 
problem.
   Welcome to point out the problem and give me some suggestion.
   hope to help the other programmers and save time.(~ ̄▽ ̄)~ 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to