MyBatis - how to create w dynamic WHERE Clause

前端 未结 2 1136
别跟我提以往
别跟我提以往 2020-12-30 16:42

The service gets an unknown object containing a list of three values ​​[column, operator, value] For example, EMAIL - like - \"TEST\"

Based on the resulting list to

2条回答
  •  Happy的楠姐
    2020-12-30 16:50

    I have been rediscovering MyBatis after a long absence myself (I was familiar with iBatis at one time). Rolf's example looks like it might be the .Net implementation, I may be wrong but I don't think the Java notation looks like that now. Rolf's tip about the literal strings is very useful.

    I've created a little class to hold your columns, operators and value and pass these into MyBatis to do the processing. The columns and operators are string literals but I have left the values as sql parameters (I imagine MyBatis would be able to do any necessary type conversion).

    public class TestAnswer {
        public static void main(String[] args) {
                ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
                SqlSessionFactory sqlFactory = (SqlSessionFactory) ctx.getBean("sqlSessionFactory");            
                MappedStatement statement = sqlFactory.getConfiguration().getMappedStatement("testAnswer");                        
    
                ArrayList params1 = new ArrayList();
                params1.add(new Clause("email","like","test"));
                params1.add(new Clause("user","<>",5));
    
                ArrayList params2 = new ArrayList();
                params2.add(new Clause("trans_id","<",100));
                params2.add(new Clause("session_id",">",500));
    
                HashMap params = new HashMap();
                params.put("params1", params1);
                params.put("params2", params2);
    
                BoundSql boundSql = statement.getBoundSql(params);
                System.out.println(boundSql.getSql());             
        }
    
        static class Clause{        
            private String column;
            private String operator;
            private Object value;
    
            public Clause(String column, String operator, Object value){
                this.column = column;
                this.operator = operator;
                this.value = value;
            }
    
            public void setColumn(String column) {this.column = column;}
            public void setOperator(String operator) {this.operator = operator;}
            public void setValue(Object value) {this.value = value;}
            public String getColumn() {return column;}
            public String getOperator() {return operator;}
            public Object getValue() {return value;}        
        }    
    }
    

    As you can see, I use Spring but I expect something similar would probably work outside of the Spring environment.

    
    
    
        
    
        
    
    
    

提交回复
热议问题